package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.ExcelConstant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.DownloadExcelTypeEnum;
import com.xbongbong.paas.enums.ExportStatusEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.ImportNeedAttrsEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.help.ImportRedisHelper;
import com.xbongbong.paas.help.ImportSendHelper;
import com.xbongbong.paas.help.PaasExcelExportHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.log.thread.LogThreadPoolBeanConfig;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ExportStatusPojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.ImportAttrPojo;
import com.xbongbong.paas.pojo.ImportStatusPojo;
import com.xbongbong.paas.pojo.QueryLinkBusinessToPutValuePojo;
import com.xbongbong.paas.pojo.dto.ColumnSetListDTO;
import com.xbongbong.paas.pojo.dto.ExcelExplainGetDTO;
import com.xbongbong.paas.pojo.dto.ExcelTemplateDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.ImportMessageFormDataDTO;
import com.xbongbong.paas.pojo.dto.UserInfoDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.ColumnSetListVO;
import com.xbongbong.paas.pojo.vo.ExcelTemplateVO;
import com.xbongbong.paas.pojo.vo.ExportCommunicateCountVO;
import com.xbongbong.paas.pojo.vo.ExportFormDataVO;
import com.xbongbong.paas.pojo.vo.ExportPartialExplainVO;
import com.xbongbong.paas.pojo.vo.ImportAttrsVO;
import com.xbongbong.paas.pojo.vo.ImportFormDataVO;
import com.xbongbong.paas.pojo.vo.ImportStatusVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.UserInfoVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.ExcelOperatorService;
import com.xbongbong.paas.service.HandleImportService;
import com.xbongbong.paas.service.PaasExcelService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.UserConfigService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.service.stage.StageHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExcelLogUtil;
import com.xbongbong.paas.util.ExcelReaderHelper;
import com.xbongbong.paas.util.ExcelUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.customerstatement.pojo.StatementTableDataExportPojo;
import com.xbongbong.pro.customerstatement.pojo.dto.StatementCustomerTableDTO;
import com.xbongbong.pro.customerstatement.pojo.vo.StatementCustomerTableVO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ImportEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.WorkReportEnum;
import com.xbongbong.pro.enums.errorcodes.ExportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkReportErrorCodeEnum;
import com.xbongbong.pro.paymenttask.pojo.dto.PaymentTaskExportDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.webexport.dto.CommunicatePlanExportDTO;
import com.xbongbong.pro.webexport.dto.CustomerStatementExportDTO;
import com.xbongbong.pro.webexport.dto.SignExportDTO;
import com.xbongbong.pro.webexport.dto.SignInExportDTO;
import com.xbongbong.pro.webexport.dto.SpecialWorkOrderExportDTO;
import com.xbongbong.pro.webexport.dto.WorkReportExportDTO;
import com.xbongbong.pro.webexport.vo.SignInExportVO;
import com.xbongbong.pro.webimport.GetAllRowPojo;
import com.xbongbong.pro.webimport.GetSingleRowPojo;
import com.xbongbong.pro.webimport.LinkFormImportPojo;
import com.xbongbong.pro.weblist.pojo.dto.CommunicatePlanDTO;
import com.xbongbong.pro.weblist.pojo.dto.NearCustomerDTO;
import com.xbongbong.pro.workorder.pojo.vo.WorkOrderDataEsListVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.export.ExportConstant;
import com.xbongbong.saas.constant.export.ImportConstant;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.CustomerSubDataEntity;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.ProductUnitPriceEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.ext.ContractSubDataExt;
import com.xbongbong.saas.domain.entity.ext.SignInEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEntityExt;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.enums.business.CreditFixedLimitEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.KnowledgeDataEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OrderOutStockEnum;
import com.xbongbong.saas.enums.business.OriStockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInstockEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WaitInstockEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.saas.enums.dictionary.CommunicatePlanStatusEnum;
import com.xbongbong.saas.enums.product.PriceSetEnum;
import com.xbongbong.saas.help.BasicHelper;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.WorkOrderListDataPermissionHelp;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.CustomerSubDataModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.service.CommunicatePlanService;
import com.xbongbong.saas.service.CustomerStatementService;
import com.xbongbong.saas.service.SaasListService;
import com.xbongbong.saas.service.SignInService;
import com.xbongbong.saas.service.WorkOrderFormDataService;
import com.xbongbong.saas.service.WorkReportService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 导入导出Service层
 *
 * @author wufeng
 * @date 2018/9/21 14:47
 */
@Service("paasExcelService")
public class PaasExcelServiceImpl implements PaasExcelService {

    private static final Logger LOG = LoggerFactory.getLogger(PaasExcelServiceImpl.class);

    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private ExcelOperatorService excelOperatorService;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private HandleImportService handleImportService;
    @Resource
    private StageHandleFactory stageHandleFactory;
    @Resource
    private EsHelper esHelper;
    @Resource
    private SaasListService saasListService;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private SignInService signInService;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private WorkOrderFormDataService workOrderFormDataService;
    @Resource
    private WorkReportService workReportService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private ExcelReaderHelper excelReaderHelper;
    @Resource
    private LogThreadPoolBeanConfig logThreadPoolBeanConfig;
    @Resource
    private ImportRedisHelper importRedisHelper;
    @Resource
    private PaasExcelExportHelp paasExcelExportHelp;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private CustomerStatementService customerStatementService;
    @Resource
    private WorkOrderListDataPermissionHelp workOrderListDataPermissionHelp;
    @Resource
    private UserService userService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private UserConfigService userConfigService;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private CommunicatePlanService communicatePlanService;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private CustomerSubDataModel customerSubDataModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private ImportSendHelper importSendHelper;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;

    @Override
    public ExcelTemplateVO templateDownLoad(ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        Workbook workbook = null;
        try {
            PaasFormExplainEntity paasFormExplainEntity;
            PaasMenuEntity paasMenuEntity;
            if (Objects.equals(excelTemplateDTO.getBusinessType(), XbbRefTypeEnum.ORI_STOCK.getCode())) {
                paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(XbbRefTypeEnum.ORI_STOCK.getCode());
                paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setName(XbbRefTypeEnum.ORI_STOCK.getName());
            } else if (Objects.equals(excelTemplateDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setName(XbbRefTypeEnum.PRICE_SET_PRODUCT.getName());
                excelTemplateDTO.setFormId(0L);
                JSONArray fieldAttrList = importHelper.getFieldAttrList(excelTemplateDTO.getCorpid());
                JSONArray fieldList = new JSONArray();
                for (int i = 0; i < fieldAttrList.size(); i++) {
                    JSONObject jsonObject = fieldAttrList.getJSONObject(i);
                    if (Objects.equals(jsonObject.getString("attr"), PriceSetEnum.PRIORITY.getAttr())) {
                        continue;
                    }
                    fieldList.add(jsonObject);
                }
                paasFormExplainEntity = new PaasFormExplainEntity();
                paasFormExplainEntity.setExplains(fieldList.toJSONString());
            } else if (Objects.equals(excelTemplateDTO.getBusinessType(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
                paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
                List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                List<String> removeAttr = KnowledgeDataEnum.getNotImportAttrList(XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
                explainList.removeIf(item -> removeAttr.contains(item.getAttr()));
                paasFormExplainEntity.setExplains(JSON.toJSONString(explainList));
                paasMenuEntity = paasMenuModel.getByKey(excelTemplateDTO.getMenuId(), excelTemplateDTO.getCorpid());
            } else {
                paasMenuEntity = paasMenuModel.getByKey(excelTemplateDTO.getMenuId(), excelTemplateDTO.getCorpid());
                if (paasMenuEntity == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
                }
                Map<String, Object> map = BeanUtil.convertBean2Map(excelTemplateDTO, true);
                List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(map);

                if (formExplainList.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                paasFormExplainEntity = formExplainList.get(0);
            }

            List<FieldAttrEntityForImport> fieldAttrList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntityForImport.class);
            excelTemplateDTO.setDistributorMark(paasFormExplainEntity.getDistributorMark());
            // 处理关联新建表单
            if (Objects.equals(excelTemplateDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                LinkFormImportPojo linkFormImportPojo = new LinkFormImportPojo();
                BeanUtil.copyProperties(excelTemplateDTO, linkFormImportPojo);
                linkFormImportPojo.setFieldAttrEntityForImportList(fieldAttrList);
                linkFormImportPojo.setFormImportOrExport(ImportConstant.FROM_IMPORT);
                handleImportService.handleLinkForm(linkFormImportPojo, paasFormExplainEntity.getDistributorMark());
            }
            // 过滤不需要导入的字段
            handleImportService.filterUnImportFields(fieldAttrList, excelTemplateDTO.getSaasMark(), ImportConstant.FROM_IMPORT, excelTemplateDTO.getBusinessType(), excelTemplateDTO.getCorpid(), excelTemplateDTO.getFormId(),excelTemplateDTO.getIsFileImport());
            // 处理公有的需要转换的字段
            FormDataListDTO formDataListDTO = new FormDataListDTO(excelTemplateDTO.getSaasMark(), excelTemplateDTO.getBusinessType(), excelTemplateDTO.getFormId());
            formDataListDTO.setCorpid(excelTemplateDTO.getCorpid());
            handleImportService.handleCommonNeedTransferFields(fieldAttrList, formDataListDTO);
            JSONArray dataExplain;
            if (Objects.equals(excelTemplateDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                // SaaS字段解释特处理
                excelTemplateDTO.setFormImportOrExport(ImportConstant.FROM_IMPORT);
                handleImportService.changeFieldShowTypeForImport(excelTemplateDTO, fieldAttrList);
                dataExplain = handleImportService.handleSpecialExplain(fieldAttrList, excelTemplateDTO);
            } else {
                fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals("extensionField",fieldAttrEntityForImport.getSaasAttr()));
                if (Objects.isNull(excelTemplateDTO.getOnlyGetAttrs())) {
                    // 不是单纯获取字段解释才要在必填字段上打*号
                    handleImportService.setTitleTag(fieldAttrList);
                }
                // 处理阶段推进器字段，获取阶段
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())) {
                        StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.PAAS.getCode(), XbbRefTypeEnum.PAAS.getCode());
                        fieldAttrEntity.setItems(stageHandle.getItemListForImport(excelTemplateDTO.getCorpid(), excelTemplateDTO.getFormId(), BasicConstant.ONE, fieldAttrEntity));
                    }
                }
                dataExplain = JSON.parseArray(JSON.toJSONString(fieldAttrList));
            }
            ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
            if (Objects.nonNull(excelTemplateDTO.getOnlyGetAttrs())) {
                excelTemplateVO.setFieldArray(dataExplain);
                return excelTemplateVO;
            }
            workbook = excelOperatorService.createExcelTemplate(excelTemplateDTO.getBusinessType(), dataExplain, paasMenuEntity.getName(), excelTemplateDTO.getExcelType(), 0, Objects.equals(BasicConstant.ONE, excelTemplateDTO.getIsFileImport()));
            excelTemplateVO.setWorkbook(workbook);
            excelTemplateVO.setName(paasMenuEntity.getName() + ImportConstant.EXCEL_SUFFIX);
            return excelTemplateVO;
        } catch (Exception e) {
            LOG.error("下载Excel错误", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }
    @Override
    public ImportAttrsVO getAttrs(ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        ImportAttrsVO importAttrsVO = null;
        try {
            excelTemplateDTO.setOnlyGetAttrs(BasicConstant.ONE);
            ExcelTemplateVO excelTemplateVO = templateDownLoad(excelTemplateDTO);
            JSONArray fieldArray = excelTemplateVO.getFieldArray();
            List<FieldAttrEntityForImport> fieldAttrEntityForImportList = JSON.parseArray(JSON.toJSONString(fieldArray), FieldAttrEntityForImport.class);
            List<String> needRequiredAttrs = ImportNeedAttrsEnum.getAttrs(excelTemplateDTO.getBusinessType());
            List<ImportAttrPojo> importAttrPojos = new ArrayList<>();
            List<Integer> needField = Arrays.asList(FieldTypeEnum.OWNERID.getType(), FieldTypeEnum.COUSERID.getType());
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                ImportAttrPojo importAttrPojo = new ImportAttrPojo();
                importAttrPojo.setAttr(fieldAttrEntityForImport.getAttr());
                importAttrPojo.setAttrName(fieldAttrEntityForImport.getAttrName());
                importAttrPojo.setRequired(fieldAttrEntityForImport.getRequired());
                if ((needRequiredAttrs.contains(fieldAttrEntityForImport.getAttr()) && Objects.equals(fieldAttrEntityForImport.getIsRedundant(), 0)) || needField.contains(fieldAttrEntityForImport.getFieldType())) {
                    // 系统指定的需要导入的字段，或者是团队字段，都需要导入
                    importAttrPojo.setNoRepeat(BasicConstant.ONE);
                } else {
                    importAttrPojo.setNoRepeat(fieldAttrEntityForImport.getNoRepeat());
                }

                importAttrPojos.add(importAttrPojo);
            }
            importAttrsVO = new ImportAttrsVO();
            importAttrsVO.setAttrPojos(importAttrPojos);
        } catch (Exception e) {
            LOG.error("PaasExcelServiceImpl.getAttrs获取导入字段报错",e);
        }
        return importAttrsVO;
    }


    @Override
    public ImportFormDataVO importFormData(ImportFormDataDTO importFormDataDTO) throws XbbException {
        String corpid = importFormDataDTO.getCorpid();
        String userId = importFormDataDTO.getUserId();
        String hashKey = corpid + "_" + userId;
        ImportStatusPojo statusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_STATUS_KEY,hashKey),ImportStatusPojo.class);
        String value = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey);
        if (statusPojo != null && !statusPojo.getFinish() && Objects.equals(value, BasicConstant.ONE_STRING)) {
            // 上次导入任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235001);
        }
        return excelReaderHelper.importExcel(importFormDataDTO);
    }

    @Override
    public ImportFormDataVO importNoSignFormData(ImportFormDataDTO importFormDataDTO) throws XbbException {
        ImportFormDataVO importFormDataVO = new ImportFormDataVO();
        // 读取导入任务状态缓存
        String hashKey = importFormDataDTO.getCorpid() + "_" + importFormDataDTO.getUserId();
        ImportStatusPojo statusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_STATUS_KEY,hashKey),ImportStatusPojo.class);
        if (statusPojo != null && !statusPojo.getFinish()) {
            // 上次导入任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235001);
        }
        // 上次导入状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_STATUS_KEY,hashKey);
        String formHashKey = hashKey + "_" + importFormDataDTO.getFormId();
        try{
            // 获取表单解释
            Map<String, Object> explainParam = BeanUtil.convertBean2Map(importFormDataDTO, true);
            explainParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(explainParam);
            if (formExplainList == null || formExplainList.isEmpty()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            PaasFormExplainEntity paasFormExplainEntity = formExplainList.get(0);
            // 获取表单字段实体
            List<FieldAttrEntityForImport> fieldAttrList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntityForImport.class);
            List<String> attrList = importFormDataDTO.getAttrList();
            if (CollectionsUtil.isNotEmpty(attrList)) {
                //过滤不需要导入的字段
                fieldAttrList.removeIf(item -> !attrList.contains(item.getAttr()));
            }
            // 处理关联新建表单
            if (Objects.equals(importFormDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                LinkFormImportPojo linkFormImportPojo = new LinkFormImportPojo();
                BeanUtil.copyProperties(importFormDataDTO, linkFormImportPojo);
                linkFormImportPojo.setFieldAttrEntityForImportList(fieldAttrList);
                linkFormImportPojo.setFormImportOrExport(ImportConstant.FROM_IMPORT);
                handleImportService.handleLinkForm(linkFormImportPojo, DistributorMarkEnum.OTHER.getCode());
            }
            // 过滤不需要导入的字段
            handleImportService.filterUnImportFields(fieldAttrList, importFormDataDTO.getSaasMark(), ImportConstant.FROM_IMPORT, importFormDataDTO.getBusinessType(), importFormDataDTO.getCorpid(), importFormDataDTO.getFormId(),importFormDataDTO.getIsFileImport());
            // 处理公有的需要转换的字段
            handleImportService.handleCommonNeedTransferFields(fieldAttrList, null);
            JSONArray jsonArray;
            if (Objects.equals(importFormDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                // SaaS字段解释特处理
                ExcelTemplateDTO excelTemplateDTO = new ExcelTemplateDTO();
                BeanUtil.copyProperties(importFormDataDTO, excelTemplateDTO);
                excelTemplateDTO.setFormImportOrExport(ImportConstant.FROM_IMPORT);
                handleImportService.changeFieldShowTypeForImport(excelTemplateDTO, fieldAttrList);
                jsonArray = handleImportService.handleSpecialExplain(fieldAttrList, excelTemplateDTO);
            } else {
                jsonArray = JSON.parseArray(JSON.toJSONString(fieldAttrList));
            }
            if (Objects.equals(importFormDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                List<CellTitlePojo> titlePojoList = JsonHelperUtil.parseArray(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_TITLE_LIST_KEY,formHashKey),CellTitlePojo.class);
//                List<String> importList = importRedisHelper.getImportList(RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_KEY, formHashKey);
//                List<RowGroupPojo> rowGroupPojoList = getRowGroupPojoListNoSign(importList);
                // 无签订人分片导入
                Runnable runnable = () -> importDataShardProcess2Mq(importFormDataDTO, titlePojoList, jsonArray, true);
                threadPoolBeanConfig.importThreadPool().execute(runnable);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("导入错误",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        return importFormDataVO;
    }

    @Override
    public ImportFormDataVO coverFormData(ImportFormDataDTO importFormDataDTO) throws XbbException {
        ImportFormDataVO importFormDataVO = new ImportFormDataVO();
        importFormDataDTO.setIsNoSignImport(BasicConstant.ONE);
        // 读取导入任务状态缓存
        String hashKey = importFormDataDTO.getCorpid() + "_" + importFormDataDTO.getUserId();
        ImportStatusPojo  statusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_STATUS_KEY,hashKey),ImportStatusPojo.class);

        String value = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey);

        if (statusPojo != null && !statusPojo.getFinish() && Objects.equals(value, BasicConstant.ONE_STRING)) {
            // 上次导入任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235001);
        }
        // 上次导入状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_STATUS_KEY,hashKey);
        long startTime = DateTimeUtil.getLong();

        paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey, BasicConstant.ONE_STRING, TimeConstant.SECONDS_EIGHT_HOUR);

        paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_LOG_TIME, hashKey, 0, RedisConstant.LONG_DURATION);
        paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_LOG_START_TIME, hashKey, startTime, RedisConstant.LONG_DURATION);
        String formHashKey = hashKey + "_" + importFormDataDTO.getFormId();
        try{
            // 获取表单解释
            Map<String, Object> explainParam = BeanUtil.convertBean2Map(importFormDataDTO, true);
            PaasFormExplainEntity paasFormExplainEntity;
            if (Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                JSONArray fieldAttrList = importHelper.getFieldAttrList(importFormDataDTO.getCorpid());
                JSONArray fieldList = new JSONArray();
                for (int i = 0; i < fieldAttrList.size(); i++) {
                    JSONObject jsonObject = fieldAttrList.getJSONObject(i);
                    if (Objects.equals(jsonObject.getString("attr"), PriceSetEnum.PRIORITY.getAttr())) {
                        continue;
                    } else if (Objects.equals(jsonObject.getString("attr"), PriceSetEnum.NAME.getAttr())) {
                        jsonObject.put("noRepeat", 1);
                    } else if (Objects.equals(jsonObject.getString("attr"), PriceSetEnum.START_TIME.getAttr())) {
                        jsonObject.put("fieldType", FieldTypeEnum.DATETIME.getType());
                    } else if (Objects.equals(jsonObject.getString("attr"), PriceSetEnum.END_TIME.getAttr())) {
                        jsonObject.put("fieldType", FieldTypeEnum.DATETIME.getType());
                    }
                    fieldList.add(jsonObject);
                }
                paasFormExplainEntity = new PaasFormExplainEntity();
                paasFormExplainEntity.setExplains(fieldList.toJSONString());
            } else {
                explainParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(explainParam);
                if (formExplainList == null || formExplainList.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                paasFormExplainEntity = formExplainList.get(0);
            }
            String explains = paasFormExplainEntity.getExplains();
            // 获取表单字段实体
            List<FieldAttrEntityForImport> fieldAttrList = JSON.parseArray(explains, FieldAttrEntityForImport.class);
            List<String> attrList = importFormDataDTO.getAttrList();
            if (CollectionsUtil.isNotEmpty(attrList)) {
                Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                List<FieldAttrEntity> fieldAttrs = JSON.parseArray(explains, FieldAttrEntity.class);
                for (FieldAttrEntity fieldAttrEntity : fieldAttrs) {
                    String attr = fieldAttrEntity.getAttr();
                    if (attrList.contains(attr)) {
                        explainMap.put(attr, fieldAttrEntity);
                    }
                }
                importFormDataDTO.setExplainMap(explainMap);
                //过滤不需要导入的字段
                fieldAttrList.removeIf(item -> !attrList.contains(item.getAttr()));
            } else {
                importFormDataDTO.setExplainMap(ExplainUtil.getExplainMap(explains, null));
            }
            // 处理关联新建表单
            importFormDataDTO.setDistributorMark(paasFormExplainEntity.getDistributorMark());
            if (Objects.equals(importFormDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                LinkFormImportPojo linkFormImportPojo = new LinkFormImportPojo();
                BeanUtil.copyProperties(importFormDataDTO, linkFormImportPojo);
                linkFormImportPojo.setFieldAttrEntityForImportList(fieldAttrList);
                linkFormImportPojo.setFormImportOrExport(ImportConstant.FROM_IMPORT);
                handleImportService.handleLinkForm(linkFormImportPojo, paasFormExplainEntity.getDistributorMark());
            }
            // 过滤不需要导入的字段
            handleImportService.filterUnImportFields(fieldAttrList, importFormDataDTO.getSaasMark(), ImportConstant.FROM_IMPORT, importFormDataDTO.getBusinessType(), importFormDataDTO.getCorpid(), importFormDataDTO.getFormId(),importFormDataDTO.getIsFileImport());
            // 处理公有的需要转换的字段

            FormDataListDTO formDataListDTO = new FormDataListDTO(importFormDataDTO.getSaasMark(), importFormDataDTO.getBusinessType(), importFormDataDTO.getFormId());
            formDataListDTO.setCorpid(importFormDataDTO.getCorpid());

            handleImportService.handleCommonNeedTransferFields(fieldAttrList, formDataListDTO);
            JSONArray jsonArray;
            if (Objects.equals(importFormDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                // SaaS字段解释特处理
                ExcelTemplateDTO excelTemplateDTO = new ExcelTemplateDTO();
                BeanUtil.copyProperties(importFormDataDTO, excelTemplateDTO);
                excelTemplateDTO.setFormImportOrExport(ImportConstant.FROM_IMPORT);
                handleImportService.changeFieldShowTypeForImport(excelTemplateDTO, fieldAttrList);
                jsonArray = handleImportService.handleSpecialExplain(fieldAttrList, excelTemplateDTO);
            } else {
                handleImportService.setTitleTag(fieldAttrList);
                jsonArray = JSON.parseArray(JSON.toJSONString(fieldAttrList));
            }
            if (Objects.equals(importFormDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                List<CellTitlePojo> titlePojoList = JsonHelperUtil.parseArray(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_TITLE_LIST_KEY,formHashKey),CellTitlePojo.class);
//                List<String> importList = importRedisHelper.getImportList(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey);
//                List<RowGroupPojo> rowGroupPojoList = getRowGroupPojoList(importList);
//                List<FieldAttrEntityForImport> fieldAttrEntityForImportList = getNeedQueryData(importFormDataDTO, jsonArray, rowGroupPojoList, titlePojoList);
                // 分片覆盖导入
                Runnable runnable = () -> importDataShardProcess2Mq(importFormDataDTO, titlePojoList, jsonArray, false);
                threadPoolBeanConfig.importThreadPool().execute(runnable);

            } else {
                // 导入PaaS数据
                List<CellTitlePojo> titlePojoList = JsonHelperUtil.parseArray(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_TITLE_LIST_KEY,formHashKey),CellTitlePojo.class);
//                List<String> importList = importRedisHelper.getImportList(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey);
//                List<RowGroupPojo> rowGroupPojoList = getRowGroupPojoList(importList);
//                List<FieldAttrEntityForImport> fieldAttrEntityForImportList = getNeedQueryData(importFormDataDTO, jsonArray, rowGroupPojoList, titlePojoList);
                // 分片覆盖导入
                Runnable runnable = () -> importDataShardProcess2Mq(importFormDataDTO, titlePojoList, jsonArray, false);
                threadPoolBeanConfig.importThreadPool().execute(runnable);
                // TODO 覆盖paas
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("导入错误",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        return importFormDataVO;
    }

    /**
     * Description:  将数据分片发送到mq处理
     * @param importFormDataDTO
     * @param jsonArray
     * @param isNoSign
     * @return void
     * @author 魏荣杰
     * @date 2019/12/13 16:01
     * @version v4.8.0
     * @since v4.8.0
     */
    public void importDataShardProcess2Mq(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, JSONArray jsonArray, boolean isNoSign) {
        // 上次导入状态缓存清除
        String hashKey = importFormDataDTO.getCorpid() + "_" + importFormDataDTO.getUserId();
        String formHashKey = hashKey + "_" + importFormDataDTO.getFormId();
//        int remainder = rowGroupPojoList.size() % ExcelConstant.PER_READ_INSERT_BATCH_COUNT;
//        int fragmentationNum = rowGroupPojoList.size() / ExcelConstant.PER_READ_INSERT_BATCH_COUNT;
//        if (remainder > 0) {
//            fragmentationNum++;
//        }

        Long importListSize = importRedisHelper.getImportListSize(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey);

        if (importListSize <= 0) {
            return;
        }

        try {
            Long remainder = importListSize % ExcelConstant.PER_READ_INSERT_BATCH_COUNT;

            Long fragmentationNum = importListSize / ExcelConstant.PER_READ_INSERT_BATCH_COUNT + 1;

            if (remainder > 0) {
                fragmentationNum++;
            }

            // 设置分片数，这边为准确数
            ImportStatusPojo importStatusPojo = new ImportStatusPojo(1, 0, 0, 0, 0, false, fragmentationNum.intValue(), importFormDataDTO.getAttrList());
            BeanUtil.copyProperties(importFormDataDTO, importStatusPojo);
            paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_STATUS_KEY, hashKey,importStatusPojo, RedisConstant.TINY_DURATION);

            long start = 0;
            int totalSize = 0;
            for (long i = 1; i <= fragmentationNum; i++) {
                long end = start + ExcelConstant.PER_READ_INSERT_BATCH_COUNT;

                List<String> importList = importRedisHelper.getImportList(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey, start, end);

                List<RowGroupPojo> rowGroupPojoList;
                if (isNoSign) {
                    rowGroupPojoList = getRowGroupPojoListNoSign(importList);
                } else {
                    rowGroupPojoList = getRowGroupPojoList(importList);
                }

                for (RowGroupPojo rowGroupPojo : rowGroupPojoList) {
                    totalSize += rowGroupPojo.getRowValueList().size();
                }

                ImportMessageFormDataDTO message = new ImportMessageFormDataDTO();
                message.setTotalSize(totalSize);
                message.setImportFormDataDTO(importFormDataDTO);
                List<ImportMessageFormDataDTO.CellTitlePojo> staticTitlePojoList = new ArrayList<>(titlePojoList.size());
                BeanUtil.copyPropertiesList(titlePojoList, staticTitlePojoList, ImportMessageFormDataDTO.CellTitlePojo.class);
                message.setTitlePojoLis(staticTitlePojoList);
                message.setJsonArray(jsonArray);
                List<ImportMessageFormDataDTO.RowGroupPojo> staticRowGroupList = new ArrayList<>(rowGroupPojoList.size());
                BeanUtil.copyPropertiesList(rowGroupPojoList, staticRowGroupList, ImportMessageFormDataDTO.RowGroupPojo.class);
                message.setRowGroupPojoList(staticRowGroupList);
                int totalRowNum = 0;
                for (RowGroupPojo groupPojo : rowGroupPojoList) {
                    totalRowNum += groupPojo.getRowValueList().size();
                }
                message.setTotalRowNum(totalRowNum);

                importSendHelper.sendMessage(message);

                start = end + 1;
            }

            if (isNoSign) {
                paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_KEY, formHashKey);
            } else {
                paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey);
            }
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.importDataShardProcess2Mq error", e);
        }

//        int totalSize = 0;
//        for (RowGroupPojo rowGroupPojo : rowGroupPojoList) {
//            totalSize += rowGroupPojo.getRowValueList().size();
//        }
//        try {
//            int size = rowGroupPojoList.size();
//            if (size > 0) {
//                ImportMessageFormDataDTO message = new ImportMessageFormDataDTO();
//                message.setTotalSize(totalSize);
//                message.setImportFormDataDTO(importFormDataDTO);
//                List<ImportMessageFormDataDTO.CellTitlePojo> staticTitlePojoList = new ArrayList<>(titlePojoList.size());
//                BeanUtil.copyPropertiesList(titlePojoList, staticTitlePojoList, ImportMessageFormDataDTO.CellTitlePojo.class);
//                message.setTitlePojoLis(staticTitlePojoList);
//                message.setJsonArray(jsonArray);
//                for (int i = 0; i < size; i += ExcelConstant.PER_READ_INSERT_BATCH_COUNT) {
//                    int toIndex = i + ExcelConstant.PER_READ_INSERT_BATCH_COUNT;
//                    if (toIndex > size) {
//                        toIndex = size;
//                    }
//                    List<RowGroupPojo> newList = rowGroupPojoList.subList(i, toIndex);
//                    List<ImportMessageFormDataDTO.RowGroupPojo> staticRowGroupList = new ArrayList<>(newList.size());
//                    BeanUtil.copyPropertiesList(newList, staticRowGroupList, ImportMessageFormDataDTO.RowGroupPojo.class);
//                    message.setRowGroupPojoList(staticRowGroupList);
//                    int totalRowNum = 0;
//                    for (RowGroupPojo groupPojo : newList) {
//                        totalRowNum += groupPojo.getRowValueList().size();
//                    }
//                    message.setTotalRowNum(totalRowNum);
//
//                    importSendHelper.sendMessage(message);
//                }
//            }
//        } catch (Exception e) {
//            LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.importDataShardProcess2Mq error", e);
//        }
    }

    /**
     * 将array转为 "List<RowGroupPojo>
     * @param rowGroupPojoListArray array
     * @return List<RowGroupPojo>
     */
    private List<RowGroupPojo> getRowGroupPojoListNoSign(List<String> rowGroupPojoListArray) {
        List<RowGroupPojo> rowGroupPojoList = new ArrayList<>();
        for (String obj : rowGroupPojoListArray) {
            JSONObject rowGroupObj = JSONObject.parseObject(obj);
            JSONObject rowGroupPojoObject = rowGroupObj.getJSONObject("rowGroupPojo");
            RowGroupPojo rowGroupPojo = new RowGroupPojo(rowGroupPojoObject.getString("groupTagValue"));
            String rowValueListStr = rowGroupPojoObject.getString("rowValueList");
            Long dataId = rowGroupPojoObject.getLong("dataId");
            JSONArray rowValueListArray = JsonHelperUtil.parseArray(rowValueListStr);
            List<List<CellValuePojo>> rowValueList = new ArrayList<>();
            for (Object rowObj : rowValueListArray) {
                JSONArray rowObject = (JSONArray)rowObj;
                List<CellValuePojo> cellValuePojos = JsonHelperUtil.parseArray(rowObject.toJSONString(),CellValuePojo.class);
                rowValueList.add(cellValuePojos);
            }
            rowGroupPojo.setRowValueList(rowValueList);
            rowGroupPojo.setDataId(dataId);
            rowGroupPojoList.add(rowGroupPojo);
        }
        return rowGroupPojoList;
    }
    /**
     * 将array转为 "List<RowGroupPojo>
     * @param rowGroupPojoListArray array
     * @return List<RowGroupPojo>
     */
    private List<RowGroupPojo> getRowGroupPojoList(List<String> rowGroupPojoListArray) {
        List<RowGroupPojo> rowGroupPojoList = new ArrayList<>();
        for (String obj : rowGroupPojoListArray) {
            JSONObject rowGroupPojoObject = JSONObject.parseObject(obj);
            RowGroupPojo rowGroupPojo = new RowGroupPojo(rowGroupPojoObject.getString("groupTagValue"));
            String rowValueListStr = rowGroupPojoObject.getString("rowValueList");
            Long dataId = rowGroupPojoObject.getLong("dataId");
            JSONArray rowValueListArray = JsonHelperUtil.parseArray(rowValueListStr);
            List<List<CellValuePojo>> rowValueList = new ArrayList<>();
            for (Object rowObj : rowValueListArray) {
                JSONArray rowObject = (JSONArray)rowObj;
                List<CellValuePojo> cellValuePojos = JsonHelperUtil.parseArray(rowObject.toJSONString(),CellValuePojo.class);
                rowValueList.add(cellValuePojos);
            }
            rowGroupPojo.setRowValueList(rowValueList);
            rowGroupPojo.setDataId(dataId);
            rowGroupPojoList.add(rowGroupPojo);
        }
        return rowGroupPojoList;
    }

    /**
     * 获取需要批量查询的数据(如联系人的关联客户一次查询出来)
     *
     * @param importFormDataDTO 入参
     * @param explainArr        解释
     * @param rowGroupPojoList  所有组的数据
     * @param titlePojoList     标题
     * @return 解释
     * @throws XbbException 异常
     */
    public List<FieldAttrEntityForImport> getNeedQueryData(ImportFormDataDTO importFormDataDTO, JSONArray explainArr, List<RowGroupPojo> rowGroupPojoList, List<CellTitlePojo> titlePojoList) throws XbbException {
        Integer businessType = importFormDataDTO.getBusinessType();
        String corpid = importFormDataDTO.getCorpid();
        List<FieldAttrEntityForImport> fieldAttrEntityForImportList = JSON.parseArray(JSON.toJSONString(explainArr), FieldAttrEntityForImport.class);
        List<String> openAttrs = new ArrayList<>();
        fieldAttrEntityForImportList.forEach(fieldAttrEntityForImport -> openAttrs.add(fieldAttrEntityForImport.getAttr()));
        List<List<CellValuePojo>> rowValueList;
        GetAllRowPojo getAllRowPojo;
        GetSingleRowPojo getSingleRowPojo;
        Integer startIndex = 0;
        // 公共查询
        queryAllUser(corpid, fieldAttrEntityForImportList);
        queryAllDept(corpid, fieldAttrEntityForImportList);
        // 经销商转换
        Integer businessType4Distributor = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, importFormDataDTO.getDistributorMark());
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType4Distributor);
        switch (redundantTemplateTypeEnum) {
            case CONTACT:
            case DISTRIBUTOR_CONTACT:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(ContactEnum.CUSTOMER_NAME.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                }
                break;
            case CUSTOMER:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(CustomerManagementEnum.PARENT.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                queryAllPurchaseableGoods(corpid, fieldAttrEntityForImportList);
                break;
            case DISTRIBUTOR_ACCOUNT:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(DistributorAccountEnum.DISTRIBUTOR_NAME.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                }
                break;
            case CONTRACT:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryLinkCustomer(ContractEnum.LINK_CUSTOMER.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(ContractEnum.LINK_CONTACT.getAttr(), null, ContactEnum.NAME.getAttr(), ContractEnum.LINK_CUSTOMER.getAttr(),null, ContactEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTACT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(ContractEnum.LINK_OPPORTUNITY.getAttr(), null, SalesOpportunityEnum.SERIAL_NO.getAttr(), ContractEnum.LINK_CUSTOMER.getAttr(), null, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY, fieldAttrEntityForImportList);
                    queryLinkCustomer(ContractEnum.LINK_PARTNER_CUSTOMER.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    //关联报价单
                    List<List<CellValuePojo>> opportunityValueList = new ArrayList<>();
                    Integer opportunityColumnIndex = importHelper.getColumnIndexByTitle(titlePojoList, ContractEnum.LINK_OPPORTUNITY.getAttrName(), null);
                    for (List<CellValuePojo> cellValueList : rowValueList) {
                        Object opportunityCellValue = importHelper.getValueByColumnIndex(cellValueList, opportunityColumnIndex);
                        if (Objects.nonNull(opportunityCellValue) && !Objects.equals(opportunityCellValue, "")) {
                            opportunityValueList.add(cellValueList);
                        }
                    }
                    if (!opportunityValueList.isEmpty()) {
                        queryHavaLinkAttrToPutValue(ContractEnum.QUOTATION_ID.getAttr(), null, QuotationEnum.QUOTATION_NO.getAttr(), ContractEnum.LINK_OPPORTUNITY.getAttr(), null, QuotationEnum.OPPORTUNITY_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_QUOTATION, fieldAttrEntityForImportList);
                    } else {
                        queryHavaLinkAttrToPutValue(ContractEnum.QUOTATION_ID.getAttr(), null, QuotationEnum.QUOTATION_NO.getAttr(), ContractEnum.LINK_CUSTOMER.getAttr(), null, QuotationEnum.CUSTOMER_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_QUOTATION, fieldAttrEntityForImportList);
                    }
                    Set<Long> enableMutilUnitParentIdSet = queryChildProductToPutValue(ContractEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    if(enableMutilUnitParentIdSet.size() > BasicConstant.ZERO){
                        Map<Long, List<ProductUnitPriceEntity>> priceEntitysByParentIdMap = productUnitPriceModel.getPriceEntitysByParentIdIn(corpid, enableMutilUnitParentIdSet);
                        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                            if (Objects.equals(ContractEnum.PRODUCT.getAttr(), fieldAttrEntityForImport.getAttr())){
                                fieldAttrEntityForImport.setProductUnitPriceEntityMap(priceEntitysByParentIdMap);
                            }
                        }
                    }
                }
                break;
            case ORDER:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryLinkCustomer(OrderEnum.LINK_DISTRIBUTOR.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    // 收货人字段
                    queryOrderLinkPartnerReceiver(OrderEnum.LINK_DISTRIBUTOR.getAttr(), OrderEnum.LINK_PARTNER_RECEIVER.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    Set<Long> enableMutilUnitParentIdSet = queryChildProductToPutValue(OrderEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    if(enableMutilUnitParentIdSet.size() > BasicConstant.ZERO){
                        Map<Long, List<ProductUnitPriceEntity>> priceEntitysByParentIdMap = productUnitPriceModel.getPriceEntitysByParentIdIn(corpid, enableMutilUnitParentIdSet);
                        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                            if (Objects.equals(OrderEnum.PRODUCT.getAttr(), fieldAttrEntityForImport.getAttr())){
                                fieldAttrEntityForImport.setProductUnitPriceEntityMap(priceEntitysByParentIdMap);
                            }
                        }
                    }
                }
                break;
            case SALES_OPPORTUNITY:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryLinkCustomer(SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(SalesOpportunityEnum.CONTACT_NAME.getAttr(), null, ContactEnum.NAME.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), null, ContactEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTACT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(SalesOpportunityEnum.DECISION_MAKER.getAttr(), null, ContactEnum.NAME.getAttr(), SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), null, ContactEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTACT, fieldAttrEntityForImportList);
                    Set<Long> enableMutilUnitParentIdSet = queryChildProductToPutValue(SalesOpportunityEnum.PRODUCTS.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    if(enableMutilUnitParentIdSet.size() > BasicConstant.ZERO){
                        Map<Long, List<ProductUnitPriceEntity>> priceEntitysByParentIdMap = productUnitPriceModel.getPriceEntitysByParentIdIn(corpid, enableMutilUnitParentIdSet);
                        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                            if (Objects.equals(SalesOpportunityEnum.PRODUCTS.getAttr(), fieldAttrEntityForImport.getAttr())){
                                fieldAttrEntityForImport.setProductUnitPriceEntityMap(priceEntitysByParentIdMap);
                            }
                        }
                    }
                }
                break;
            case SUPPLIER:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(SupplierEnum.PRODUCT_LIST.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }

                break;
            case SUPPLIER_CONTACT:
                break;
            case BOMBILL:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(BomBillEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryChildProductToPutValue(BomBillEnum.MATERIEL.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case PRODUCTIONORDER:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(ProductionOrderEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryChildProductToPutValue(ProductionOrderEnum.MATERIEL.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryLinkBusinessToPutValueAllField(ProductionOrderEnum.BOM_ID.getAttr(), null, BomBillEnum.SHEET_NO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_BOM, fieldAttrEntityForImportList);
                }
                break;
            case COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    // 过滤线索数据列
                    fifterClueRowsValue(titlePojoList, rowValueList);
                    queryLinkCustomer(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(CustomerCommunicateEnum.CONTACT_ARRAY.getAttr(), null, ContactEnum.NAME.getAttr(), CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), null, ContactEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTACT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_ID.getAttr(), null, CommunicatePlanEnum.NAME.getAttr(), CustomerCommunicateEnum.CUSTOMER_NAME.getAttr(), null, CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN, fieldAttrEntityForImportList);
                    if (!openAttrs.contains(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr())) {
                        break;
                    }
                    // 查询
                    queryLinkClue(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);

                    List<List<CellValuePojo>> contractValueList = new ArrayList<>();
                    List<List<CellValuePojo>> opportunityValueList = new ArrayList<>();
                    Integer columnIndex = getColumnIndexWithSubAttr(titlePojoList, fieldAttrEntityForImportList, CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttr());
                    for (List<CellValuePojo> cellValueList : rowValueList) {
                        Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
                        if (Objects.nonNull(cellValue)) {
                            cellValue = cellValue.toString();
                            if (Objects.equals(cellValue, XbbRefTypeEnum.CONTRACT.getName()) || Objects.equals(cellValue, XbbRefTypeEnum.ORDER.getName())) {
                                contractValueList.add(cellValueList);
                            } else if (Objects.equals(cellValue, XbbRefTypeEnum.SALES_OPPORTUNITY.getName())) {
                                opportunityValueList.add(cellValueList);
                            }
                        }
                    }
                    if (!contractValueList.isEmpty()) {
                        queryLinkBusinessToPutValue(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), ImportEnum.COMMUNICATE_NAME.getAttr(), ContractEnum.CONTRACT_NO.getAttr(), titlePojoList, corpid, contractValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                    }
                    if (!opportunityValueList.isEmpty()) {
                        queryLinkBusinessToPutValue(CustomerCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), ImportEnum.COMMUNICATE_NAME.getAttr(), SalesOpportunityEnum.SERIAL_NO.getAttr(), titlePojoList, corpid, opportunityValueList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY, fieldAttrEntityForImportList);
                    }
                }
               break;
            case JXC_COMMUNICATE:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkBusinessToPutValue(SupplierCommunicateEnum.SUPPLIER_CONTACT.getAttr(), null, SupplierContactEnum.NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT, fieldAttrEntityForImportList);
                    if (!openAttrs.contains(SupplierCommunicateEnum.COMMUNICATE_BUSINESS.getAttr())) {
                        break;
                    }
                    queryLinkBusinessToPutValue(SupplierCommunicateEnum.COMMUNICATE_BUSINESS.getAttr(), ImportEnum.COMMUNICATE_NAME.getAttr(), PurchaseEnum.SHEET_NO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PURCHASE, fieldAttrEntityForImportList);
                }
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(PurchaseInstockEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryLinkBusinessToPutValue(PurchaseInstockEnum.SUPPLIER_ID.getAttr(), null, SupplierEnum.SUPPLIER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(PurchaseInstockEnum.REF_ID.getAttr(), null, PurchaseEnum.SHEET_NO.getAttr(), PurchaseInstockEnum.SUPPLIER_ID.getAttr(), null, PurchaseEnum.SUPPLIER_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PURCHASE, fieldAttrEntityForImportList);
                    queryProductToPutValue(PurchaseInstockEnum.REF_ID.getAttr(), businessType, corpid, PurchaseInstockEnum.SHEET_NO.getAttr(), fieldAttrEntityForImportList);
                }
                break;
            case OTHER_INSTOCK:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(InstockEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case OTHER_OUTSTOCK:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(ContractOutstockEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case CONTRACT_OUTSTOCK:
            case ORDER_OUTSTOCK:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryLinkCustomer(ContractOutstockEnum.LINK_CUSTOMER.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(ContractOutstockEnum.REF_ID.getAttr(), null, ContractEnum.CONTRACT_NO.getAttr(), ContractOutstockEnum.LINK_CUSTOMER.getAttr(), null, ContractEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                    Set<Long> enableMutilUnitParentIdSet = queryChildProductToPutValue(ContractOutstockEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    if(enableMutilUnitParentIdSet.size() > BasicConstant.ZERO){
                        Map<Long, List<ProductUnitPriceEntity>> priceEntitysByParentIdMap = productUnitPriceModel.getPriceEntitysByParentIdIn(corpid, enableMutilUnitParentIdSet);
                        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                            if (Objects.equals(ContractOutstockEnum.PRODUCT.getAttr(), fieldAttrEntityForImport.getAttr())){
                                fieldAttrEntityForImport.setProductUnitPriceEntityMap(priceEntitysByParentIdMap);
                            }
                        }
                    }
                    queryProductToPutValue(ContractOutstockEnum.REF_ID.getAttr(), businessType, corpid, ContractOutstockEnum.SHEET_NO.getAttr(), fieldAttrEntityForImportList);
                    if (Objects.equals(redundantTemplateTypeEnum, RedundantTemplateTypeEnum.ORDER_OUTSTOCK)) {
                        queryOrderLinkPartnerReceiver(OrderOutStockEnum.LINK_DISTRIBUTOR.getAttr(), OrderOutStockEnum.LINK_PARTNER_RECEIVER.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                        queryOrderLinkPartnerReceiver(OrderOutStockEnum.LINK_DISTRIBUTOR.getAttr(), OrderOutStockEnum.SEND_NAME.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    }
                }
                break;
            case PRODUCT:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryLinkBusinessToPutValue(ProductEnum.SUPPLIER.getAttr(), null, SupplierEnum.SUPPLIER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER, fieldAttrEntityForImportList);
                    queryLinkBusinessToPutValue(ProductEnum.WAREHOUSE.getAttr(), null, WarehouseEnum.WAREHOUSE_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_WAREHOUSE, fieldAttrEntityForImportList);
                }
                break;
            case INVENTORY:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(InventoryEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case ASSEMBLE:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(AssembleEnum.OUT_PRODUCTS.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryChildProductToPutValue(AssembleEnum.IN_PRODUCTS.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case TRANSFER:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(TransferEnum.PRODUCTS.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case INVOICE:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(InvoiceEnum.CUSTOMER_NAME.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(InvoiceEnum.CONTRACT_ID.getAttr(), null, ContractEnum.CONTRACT_NO.getAttr(), InvoiceEnum.CUSTOMER_NAME.getAttr(), null, ContractEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(InvoiceEnum.PAYMENT_ID.getAttr(), null, PaymentEnum.PAYMENT_NO.getAttr(), InvoiceEnum.CUSTOMER_NAME.getAttr(), null, PaymentEnum.CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PAYMENT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(InvoiceEnum.PAYMENT_ID.getAttr(),null,PaymentEnum.PAYMENT_NO.getAttr(),InvoiceEnum.CONTRACT_ID.getAttr(),null,PaymentEnum.CONTRACT.getAttr(),titlePojoList,corpid,rowValueList,IndexTypeEnum.IDX_SAAS_PAYMENT,fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(InvoiceEnum.PAYMENT_SHEET_ID.getAttr(),null,PaymentSheetEnum.SHEET_NO.getAttr(),InvoiceEnum.CUSTOMER_NAME.getAttr(),null,PaymentSheetEnum.CUSTOMER_ID.getAttr(),titlePojoList,corpid,rowValueList,IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET,fieldAttrEntityForImportList);
                }
                break;
            case PURCHASE_INVOICE:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkBusinessToPutValue(PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(), null, SupplierEnum.SUPPLIER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(PurchaseInvoiceEnum.PURCHASE_ID.getAttr(), null, PurchaseEnum.SHEET_NO.getAttr(),PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(), null, PurchaseEnum.SUPPLIER_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PURCHASE, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr(), null, PayPlanEnum.PAY_PLAN_NO.getAttr(), PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(), null, PayPlanEnum.LINK_SUPPLIER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PAY_PLAN, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr(),null,PayPlanEnum.PAY_PLAN_NO.getAttr(),PurchaseInvoiceEnum.PURCHASE_ID.getAttr(),null,PayPlanEnum.LINK_PURCHASE.getAttr(),titlePojoList,corpid,rowValueList,IndexTypeEnum.IDX_SAAS_PAY_PLAN,fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr(),null,PaySheetEnum.PAY_PLAN_NO.getAttr(),PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr(),null,PaySheetEnum.LINK_SUPPLIER.getAttr(),titlePojoList,corpid,rowValueList,IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET,fieldAttrEntityForImportList);
                }
                break;
            case RETURNED_PURCHASE:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    // 关联产品
                    Set<Long> enableMutilUnitParentIdSet = queryChildProductToPutValue(ReturnedPurchaseEnum.PRODUCTS.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    // 关联采购合同
                    queryLinkBusinessToPutValue(ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr(), null, PurchaseEnum.SHEET_NO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PURCHASE, fieldAttrEntityForImportList);
                }
                break;
            case PURCHASE:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    // 关联产品
                    queryChildProductToPutValue(PurchaseEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryLinkBusinessToPutValue(PurchaseEnum.SUPPLIER_ID.getAttr(), null, SupplierEnum.SUPPLIER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER, fieldAttrEntityForImportList);
                }
                break;
            case REFUND:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryLinkCustomer(RefundEnum.CUSTOMER_ID.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(RefundEnum.CONTRACT_ID.getAttr(), null, ContractEnum.CONTRACT_NO.getAttr(), RefundEnum.CUSTOMER_ID.getAttr(),null, ContractEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(RefundEnum.PAYMENT_SHEETS.getAttr(), null, PaymentSheetEnum.SHEET_NO.getAttr(), RefundEnum.CONTRACT_ID.getAttr(), null, PaymentSheetEnum.CONTRACT.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(RefundEnum.INVOICES.getAttr(), null, InvoiceEnum.SHEET_NO.getAttr(), RefundEnum.CONTRACT_ID.getAttr(), null, InvoiceEnum.CONTRACT_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_INVOICE, fieldAttrEntityForImportList);
                    queryChildProductToPutValue(RefundEnum.PRODUCTS.getAttr(),SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    queryHavaLinkAttrToPutValue(RefundEnum.PAYMENTS.getAttr(), null, PaymentEnum.PAYMENT_NO.getAttr(), RefundEnum.CONTRACT_ID.getAttr(), null, PaymentEnum.CONTRACT.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PAYMENT, fieldAttrEntityForImportList);
                }
                break;
            case PAYMENT:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    // 关联客户
                    queryLinkCustomer(PaymentEnum.CUSTOMER.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
	                queryHavaLinkAttrToPutValue(PaymentEnum.CONTRACT.getAttr(), null, ContractEnum.CONTRACT_NO.getAttr(), PaymentEnum.CUSTOMER.getAttr(),null, ContractEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                }
                break;
            case PAY_PLAN:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryHavaLinkAttrToPutValue(PayPlanEnum.LINK_PURCHASE.getAttr(), null, PurchaseEnum.SHEET_NO.getAttr(), PayPlanEnum.LINK_SUPPLIER.getAttr(),null, PurchaseEnum.SUPPLIER_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PURCHASE, fieldAttrEntityForImportList);
                    queryLinkBusinessToPutValue(PurchaseEnum.SUPPLIER_ID.getAttr(), null, SupplierEnum.SUPPLIER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER, fieldAttrEntityForImportList);
                }
                break;

            case QUOTATION:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    //关联客户
                    queryLinkCustomer(QuotationEnum.CUSTOMER_ID.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    //关联联系人
                    queryHavaLinkAttrToPutValue(QuotationEnum.CONTACT_ID.getAttr(), null, ContactEnum.NAME.getAttr(), QuotationEnum.CUSTOMER_ID.getAttr(), null, ContactEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTACT, fieldAttrEntityForImportList);
                    //关联机会
                    queryHavaLinkAttrToPutValue(QuotationEnum.OPPORTUNITY_ID.getAttr(), null, SalesOpportunityEnum.SERIAL_NO.getAttr(), QuotationEnum.CUSTOMER_ID.getAttr(), null, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_OPPORTUNITY, fieldAttrEntityForImportList);
                    // 关联产品
                    Set<Long> enableMutilUnitParentIdSet = queryChildProductToPutValue(QuotationEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    if(enableMutilUnitParentIdSet.size() > BasicConstant.ZERO){
                        Map<Long, List<ProductUnitPriceEntity>> priceEntitysByParentIdMap = productUnitPriceModel.getPriceEntitysByParentIdIn(corpid, enableMutilUnitParentIdSet);
                        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                            if (Objects.equals(QuotationEnum.PRODUCT.getAttr(), fieldAttrEntityForImport.getAttr())){
                                fieldAttrEntityForImport.setProductUnitPriceEntityMap(priceEntitysByParentIdMap);
                            }
                        }
                    }
                }
                break;
            case ORI_STOCK:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(OriStockEnum.PRODUCT_DETAIL.getAttr(),SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case PAYMENT_SHEET:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    // 关联客户
                    queryLinkCustomer(PaymentSheetEnum.CUSTOMER_ID.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    //关联合同
                    queryHavaLinkAttrToPutValue(PaymentSheetEnum.CONTRACT.getAttr(), null, ContractEnum.CONTRACT_NO.getAttr(), PaymentSheetEnum.CUSTOMER_ID.getAttr(),null, ContractEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                    //关联应收款
                    queryHavaLinkAttrToPutValue(PaymentSheetEnum.PAYMENT.getAttr(), null, PaymentEnum.PAYMENT_NO.getAttr(), PaymentSheetEnum.CONTRACT.getAttr(),null, PaymentEnum.CONTRACT.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PAYMENT, fieldAttrEntityForImportList);
                }
                break;
            case PAY_SHEET:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    // 关联供应商
                    queryLinkBusinessToPutValue(PaySheetEnum.LINK_SUPPLIER.getAttr(), null, SupplierEnum.SUPPLIER_NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_SUPPLIER, fieldAttrEntityForImportList);
                    //关联采购合同
                    queryHavaLinkAttrToPutValue(PaySheetEnum.LINK_PURCHASE.getAttr(), null, PurchaseEnum.SHEET_NO.getAttr(), PaySheetEnum.LINK_SUPPLIER.getAttr(),null, PurchaseEnum.SUPPLIER_ID.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PURCHASE, fieldAttrEntityForImportList);
                    //关联付款计划
                    queryHavaLinkAttrToPutValue(PaySheetEnum.PAY_PLAN.getAttr(), null, PayPlanEnum.PAY_PLAN_NO.getAttr(), PaySheetEnum.LINK_PURCHASE.getAttr(),null, PayPlanEnum.LINK_PURCHASE.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PAY_PLAN, fieldAttrEntityForImportList);
                }
                break;
            case CLUE:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkBusinessToPutValue(ClueEnum.MARKET_ACTIVITY_ID.getAttr(), null, MarketActivityEnum.NAME.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY, fieldAttrEntityForImportList);
                }
                break;
            case PRICE_SET:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(PriceSetEnum.PRODUCT.getAttr(),SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case CREDIT_LIMIT:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(CreditLimitEnum.CUSTOMER_ID.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                }
                break;
            case CREDIT_TEMPORARY_LIMIT:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(CreditTemporaryLimitEnum.CUSTOMER_ID.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                }
                break;
            case CREDIT_FIXED_LIMIT:
                while (startIndex < rowGroupPojoList.size()) {
                    getSingleRowPojo = getGroupFirstRowValue(rowGroupPojoList, startIndex);
                    startIndex = getSingleRowPojo.getStartIndex();
                    rowValueList = getSingleRowPojo.getSingleRowValueList();
                    queryLinkCustomer(CreditFixedLimitEnum.CUSTOMER_ID.getAttr(), corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                }
                break;
            case COST_ADJUST:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    queryChildProductToPutValue(CostAdjustEnum.PRODUCT.getAttr(), SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                }
                break;
            case WORK_ORDER_V2:
                while (startIndex < rowGroupPojoList.size()) {
                    getAllRowPojo = getAllRowValueList(rowGroupPojoList, startIndex);
                    rowValueList = getAllRowPojo.getAllRowValueList();
                    startIndex = getAllRowPojo.getStartIndex();
                    // 关联客户
                    queryLinkCustomer("text_2", corpid, titlePojoList, rowValueList, fieldAttrEntityForImportList);
                    // 关联产品
                    queryChildProductToPutValue("array_1", SelectProductEnum.PRODUCT_NO.getAttr(), ProductEnum.SERIALNO.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldAttrEntityForImportList);
                    // 关联合同
                    queryHavaLinkAttrToPutValue("text_81", null, ContractEnum.CONTRACT_NO.getAttr(), "text_2", null, ContractEnum.LINK_CUSTOMER.getAttr(), titlePojoList, corpid, rowValueList, IndexTypeEnum.IDX_SAAS_CONTRACT, fieldAttrEntityForImportList);
                }
                break;
            default:
                break;
        }
        return fieldAttrEntityForImportList;
    }

    /**
     * 过滤销售线索跟进记录导入非法数据列
     * @param titlePojoList
     * @param rowValueList
     */
    private void fifterClueRowsValue(List<CellTitlePojo> titlePojoList, List<List<CellValuePojo>> rowValueList){
        Map<String, Integer> map = new HashMap<>();
        titlePojoList.forEach(item -> map.put(item.getTitle(),item.getColumnIndex()));
        Integer customerNameIndex = map.get(ImportEnum.LINK_CUSTOMER_NAME.getAttrName());
        Integer customerPhoneIndex = map.get(ImportEnum.LINK_CUSTOMER_PHONE.getAttrName());
        Integer contactIndex = map.get(CustomerCommunicateEnum.CONTACT_ARRAY.getAttrName());
        Integer finishCommunicatePlanIdIndex = map.get(CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_ID.getAttrName());
        Integer businessTypeIndex = map.get(ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttrName());
        if (Objects.isNull(businessTypeIndex)){
            LOG.error("businessTypeIndex is null");
            return;
        }
        for (List<CellValuePojo> cellValuePojoList : rowValueList) {
            CellValuePojo cellValuePojo = cellValuePojoList.get(businessTypeIndex);
            String title = cellValuePojo.getTitle();
            Object value = cellValuePojo.getValue();
            if (StringUtil.isNotEmpty(title) && Objects.equals(title, ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttrName()) && Objects.equals(value, XbbRefTypeEnum.CLUE.getName())){
                if (Objects.nonNull(customerNameIndex)){
                    CellValuePojo customerNamePojo = cellValuePojoList.get(customerNameIndex);
                    Object customerName = customerNamePojo.getValue();
                    if (Objects.nonNull(customerName) && StringUtil.isNotEmpty(customerName.toString())){
                        customerNamePojo.setValue("");
                    }
                }
                if (Objects.nonNull(customerPhoneIndex)){
                    CellValuePojo customerPhonePojo = cellValuePojoList.get(customerPhoneIndex);
                    Object customerPhone = customerPhonePojo.getValue();
                    if (Objects.nonNull(customerPhone) && StringUtil.isNotEmpty(customerPhone.toString())){
                        customerPhonePojo.setValue("");
                    }
                }
                if (Objects.nonNull(contactIndex)){
                    CellValuePojo contactPojo = cellValuePojoList.get(contactIndex);
                    Object contact = contactPojo.getValue();
                    if (Objects.nonNull(contact) && StringUtil.isNotEmpty(contact.toString())){
                        contactPojo.setValue("");
                    }
                }
                if (Objects.nonNull(finishCommunicatePlanIdIndex)){
                    CellValuePojo communicatePlanPojo = cellValuePojoList.get(finishCommunicatePlanIdIndex);
                    Object communicatePlan = communicatePlanPojo.getValue();
                    if (Objects.nonNull(communicatePlan) && StringUtil.isNotEmpty(communicatePlan.toString())){
                        communicatePlanPojo.setValue("");
                    }
                }
            }
        }
    }

    private GetSingleRowPojo getGroupFirstRowValue(List<RowGroupPojo> rowGroupPojoList, Integer startIndex) {
        GetSingleRowPojo getSingleRowPojo = new GetSingleRowPojo();
        List<List<CellValuePojo>> groupFirstRowValueList = new ArrayList<>();
        Integer rowSize = 0;
        for (int i = startIndex; i < rowGroupPojoList.size(); i++) {
            RowGroupPojo rowGroupPojo = rowGroupPojoList.get(i);
            List<CellValuePojo> rowValueList = rowGroupPojo.getRowValueList().get(0);
            ++ rowSize;
            if (rowSize > ImportConstant.GROUP_EXCEL_IMPORT_COUNT) {
                break;
            }
            startIndex ++;
            groupFirstRowValueList.add(rowValueList);
        }
        getSingleRowPojo.setStartIndex(startIndex);
        getSingleRowPojo.setSingleRowValueList(groupFirstRowValueList);
        return getSingleRowPojo;
    }

    private GetAllRowPojo getAllRowValueList(List<RowGroupPojo> rowGroupPojoList, int startIndex) {
        GetAllRowPojo getAllRowPojo = new GetAllRowPojo();
        Integer rowSize = 0;
        List<List<CellValuePojo>> allRowValueList = new ArrayList<>();
        for (int i = startIndex; i< rowGroupPojoList.size(); i ++) {
            RowGroupPojo rowGroupPojo = rowGroupPojoList.get(i);
            List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
            rowSize += rowValueList.size();
            // 留一定的预留空间,防止一组数据过大
            if (rowSize > 950) {
                break;
            }
            startIndex ++;
            allRowValueList.addAll(rowValueList);
        }
        getAllRowPojo.setStartIndex(startIndex);
        getAllRowPojo.setAllRowValueList(allRowValueList);
        getAllRowPojo.setRowSize(rowSize);
        return getAllRowPojo;
    }

    /**
     * 获取索引根据子attr
     *
     * @param titlePojoList
     * @param fieldAttrEntityForImportList
     * @param attr
     * @param subAttr
     * @return
     */
    private Integer getColumnIndexWithSubAttr(List<CellTitlePojo> titlePojoList, List<FieldAttrEntityForImport> fieldAttrEntityForImportList, String attr, String subAttr) {
        FieldAttrEntityForImport fieldAttrEntityForImport = new FieldAttrEntityForImport();
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
                break;
            }
        }
        Integer columnIndex;
        String title = null;
        String parentTitle = fieldAttrEntityForImport.getAttrName();
        List<? extends FieldAttrEntity> items = fieldAttrEntityForImport.getSubForm().getItems();
        for (int i = 0; i < items.size(); i++) {
            if (Objects.equals(subAttr, items.get(i).getAttr())) {
                title = items.get(i).getAttrName();
                break;
            }
        }
        columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, title, parentTitle);
        return columnIndex;
    }
    /**
     * es批量查询数据封装到解释
     *
     * @param attr                         属性
     * @param titlePojoList                标题
     * @param corpid                       公司id
     * @param rowValueList                 每组第一条数据的集合
     * @param fieldAttrEntityForImportList 解释
     * @throws XbbException 异常
     */
    private FieldAttrEntityForImport queryLinkCustomer(String attr, String corpid, List<CellTitlePojo> titlePojoList, List<List<CellValuePojo>> rowValueList, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        FieldAttrEntityForImport fieldAttrEntityForImport = null;
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
                break;
            }
        }
        if (Objects.isNull(fieldAttrEntityForImport)) {
            return new FieldAttrEntityForImport();
        }
        String parentTitle = fieldAttrEntityForImport.getAttrName();
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        List<Object> nameAttrValues = new ArrayList<>();
        List<Object> phoneAttrValues = new ArrayList<>();
        Integer customerNamecolumnIndex = importHelper.getColumnIndexByTitle(titlePojoList, ImportEnum.LINK_CUSTOMER_NAME.getAttrName(), parentTitle);
        Integer customerPhonecolumnIndex = importHelper.getColumnIndexByTitle(titlePojoList, ImportEnum.LINK_CUSTOMER_PHONE.getAttrName(), parentTitle);
        List<String> onlyNameKeyList = new ArrayList<>();
        List<String> onlyPhoneKeyList = new ArrayList<>();
        List<String> namePhoneKeyList = new ArrayList<>();
        List<String> namePhoneKeySplitPhoneList = new ArrayList<>();
        for (List<CellValuePojo> cellValueList : rowValueList) {
            String uniqueKey = "";
            Object nameCellValue = importHelper.getValueByColumnIndex(cellValueList, customerNamecolumnIndex);
            Object phoneCellValue = importHelper.getValueByColumnIndex(cellValueList, customerPhonecolumnIndex);
            boolean nameNotEmpty = Objects.nonNull(nameCellValue) && StringUtil.isNotEmpty(nameCellValue.toString());
            boolean phoneNotEmpty = Objects.nonNull(phoneCellValue) && StringUtil.isNotEmpty(phoneCellValue.toString());
            if (nameNotEmpty && phoneNotEmpty) {
                // fix: 26598 【成功部】导入联系人的时候，关联客户中写的客户名称前面或则后面有空格的话，会无法匹配，需要直接导入的时候前后空格去掉，包括其他的单据，例如合同、销售机会、报价单等
                nameAttrValues.add(nameCellValue.toString().trim());
                phoneAttrValues.add(phoneCellValue.toString().trim());
                uniqueKey = uniqueKey + nameCellValue.toString().trim() + StringConstant.IMPORT_SPLIT + phoneCellValue.toString().trim();
                namePhoneKeyList.add(uniqueKey);
            } else if (phoneNotEmpty) {
                phoneAttrValues.add(phoneCellValue.toString().trim());
                uniqueKey = uniqueKey + phoneCellValue.toString().trim();
                onlyPhoneKeyList.add(uniqueKey);
            } else if (nameNotEmpty) {
                nameAttrValues.add(nameCellValue.toString().trim());
                uniqueKey = uniqueKey + nameCellValue.toString().trim();
                onlyNameKeyList.add(uniqueKey);
            }
        }
        Map<String, Object> map = fieldAttrEntityForImport.getLinkBusinessMap();
        if (Objects.isNull(map)) {
            map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        List<String> repeatKey = fieldAttrEntityForImport.getRepeatErrorKey();
        if (Objects.isNull(repeatKey)) {
            repeatKey = new ArrayList<>();
        }
        if (nameAttrValues.isEmpty()) {
            fieldAttrEntityForImport.setRepeatErrorKey(repeatKey);
            fieldAttrEntityForImport.setLinkBusinessMap(map);
            return fieldAttrEntityForImport;
        }
        for (String namePhone : namePhoneKeyList) {
            String[] split = namePhone.split("\\^");
            String phone = split[1];
            namePhoneKeySplitPhoneList.add(phone);
        }
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(StringConstant.FLOW_STATUS, FlowStatusEnum.normalStatus()));
        boolQueryBuilder.should(termsQuery(esData + CustomerManagementEnum.NAME.getAttr() + keyword, nameAttrValues));
        boolQueryBuilder.should(termsQuery(esData + CustomerManagementEnum.PHONE.getAttr() + StringConstant.POINT + StringConstant.PHONE_TEL_ATTR + keyword, phoneAttrValues));
        boolQueryBuilder.minimumShouldMatch(EsNormalConstant.MINI_MUM_SHOULD_MATCH);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
        List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, null);

        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityList) {
            String customerName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerManagementEnum.NAME.getAttr(), "");
            JSONArray phoneJsonArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
            List<String> phoneList = new ArrayList<>();
            for (Object object : phoneJsonArray) {
                JSONObject phoneJsonObject = (JSONObject) object;
                String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                phoneList.add(tel);
            }
            String key = "";
            if (onlyNameKeyList.contains(customerName)) {
                key = customerName;
                if (map.containsKey(key)) {
                    PaasFormDataEntityExt entityExt = (PaasFormDataEntityExt)map.get(key);
                    if (!Objects.equals(entityExt.getId(), paasFormDataEntityExt.getId())) {
                        repeatKey.add(key);
                    }
                }
                map.put(key, paasFormDataEntityExt);
            } else {
                for (String tel : phoneList) {
                    boolean havePhoneKey = false;
                    if (onlyPhoneKeyList.contains(tel)) {
                        key = tel;
                        havePhoneKey = true;
                    }
                    if (namePhoneKeySplitPhoneList.contains(tel)) {
                        key = customerName + tel;
                        havePhoneKey = true;
                    }
                    if (havePhoneKey) {
                        if (map.containsKey(key)) {
                            PaasFormDataEntityExt entityExt = (PaasFormDataEntityExt)map.get(key);
                            if (!Objects.equals(entityExt.getId(), paasFormDataEntityExt.getId())) {
                                repeatKey.add(key);
                            }
                        }
                        map.put(key, paasFormDataEntityExt);
                    }
                }
            }
        }
        fieldAttrEntityForImport.setRepeatErrorKey(repeatKey);
        fieldAttrEntityForImport.setLinkBusinessMap(map);
        return fieldAttrEntityForImport;
    }

    /**
     * es批量查询线索数据封装到解释
     * 查线索
     * 验重
     * @param attr                         属性
     * @param titlePojoList                标题
     * @param corpid                       公司id
     * @param rowValueList                 数据行集合
     * @param fieldAttrEntityForImportList 解释
     * @throws XbbException 异常
     */
    private FieldAttrEntityForImport queryLinkClue(String attr, String corpid, List<CellTitlePojo> titlePojoList, List<List<CellValuePojo>> rowValueList, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        FieldAttrEntityForImport fieldAttrEntityForImport = null;
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
                break;
            }
        }
        if (Objects.isNull(fieldAttrEntityForImport)) {
            return new FieldAttrEntityForImport();
        }
        String parentTitle = fieldAttrEntityForImport.getAttrName();
        List<Object> nameAttrValues = new ArrayList<>();
        Integer businessNameIndex = importHelper.getColumnIndexByTitle(titlePojoList, ImportEnum.COMMUNICATE_NAME.getAttrName(), parentTitle);
        Integer businessTypeIndex = importHelper.getColumnIndexByTitle(titlePojoList, ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttrName(), parentTitle);
        List<String> nameKeyList = new ArrayList<>();
        // 取出所有的线索名称值
        for (List<CellValuePojo> cellValueList : rowValueList) {

            String uniqueKey = "";
            Object nameCellValue = importHelper.getValueByColumnIndex(cellValueList, businessNameIndex);
            Object typeCellValue = importHelper.getValueByColumnIndex(cellValueList, businessTypeIndex);
            boolean nameNotEmpty = Objects.nonNull(nameCellValue) && StringUtil.isNotEmpty(nameCellValue.toString());
            boolean typeNotEmpty = Objects.nonNull(typeCellValue) && StringUtil.isNotEmpty(typeCellValue.toString());
            // 销售线索导入
            if (typeNotEmpty && Objects.equals(typeCellValue, XbbRefTypeEnum.CLUE.getName()) && nameNotEmpty){
                nameAttrValues.add(nameCellValue.toString().trim());
                uniqueKey = uniqueKey + nameCellValue.toString().trim();
                nameKeyList.add(uniqueKey);
            }
        }
        Map<String, Object> map = fieldAttrEntityForImport.getLinkBusinessMap();
        if (Objects.isNull(map)) {
            map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        List<String> repeatKey = fieldAttrEntityForImport.getRepeatErrorKey();
        if (Objects.isNull(repeatKey)) {
            repeatKey = new ArrayList<>();
        }
        if (nameAttrValues.isEmpty()) {
            fieldAttrEntityForImport.setRepeatErrorKey(repeatKey);
            fieldAttrEntityForImport.setLinkBusinessMap(map);
            return fieldAttrEntityForImport;
        }
        // 根据客户名称查询es
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.should(termsQuery(esData + ClueEnum.COMPANY_NAME.getAttr() + keyword, nameAttrValues));
        boolQueryBuilder.minimumShouldMatch(EsNormalConstant.MINI_MUM_SHOULD_MATCH);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, XbbRefTypeEnum.CLUE.getCode(), SaasMarkEnum.SAAS.getCode());
        List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, null);

        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityList) {
            String companyName = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), ClueEnum.COMPANY_NAME.getAttr(), "");
            String key = "";
            if (nameKeyList.contains(companyName)) {
                key = companyName;
                if (map.containsKey(key)) {
                    PaasFormDataEntityExt entityExt = (PaasFormDataEntityExt)map.get(key);
                    if (!Objects.equals(entityExt.getId(), paasFormDataEntityExt.getId())) {
                        repeatKey.add(key);
                    }
                }
                map.put(key, paasFormDataEntityExt);
            }
        }
        fieldAttrEntityForImport.setRepeatErrorKey(repeatKey);
        fieldAttrEntityForImport.setLinkBusinessMap(map);
        return fieldAttrEntityForImport;
    }

    /**
     * 查询经销商关联的收货人
     */
    private void queryOrderLinkPartnerReceiver(String relyAttr, String attr, String corpid, List<CellTitlePojo> titlePojoList, List<List<CellValuePojo>> rowValueList, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        FieldAttrEntityForImport linkDistributorFieldAttrEntity = null;
        FieldAttrEntityForImport fieldAttrEntityForImport = null;
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
            }
            if (Objects.equals(needQueryAttrEntity.getAttr(), relyAttr)) {
                linkDistributorFieldAttrEntity = needQueryAttrEntity;
            }
        }
        if (Objects.isNull(linkDistributorFieldAttrEntity)) {
            return;
        }
        Map<String, Object> linkBusinessMap = linkDistributorFieldAttrEntity.getLinkBusinessMap();
        if (linkBusinessMap.isEmpty()) {
            return;
        }
        List<Object> linkDistributorList = new ArrayList<>(linkBusinessMap.values());
        List<Long> distributorIdList = new ArrayList<>();
        for (Object linkDistributor : linkDistributorList) {
            PaasFormDataEntityExt distributor = (PaasFormDataEntityExt) linkDistributor;
            distributorIdList.add(distributor.getId());
        }

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("dataIdIn", distributorIdList);
        param.put("del", DelEnum.NORMAL.getDel());
        List<CustomerSubDataEntity> entitys = customerSubDataModel.findEntitys(param);
        //收货地址集合
        Map<Long, List<ContractSubDataExt>> shippingAddressMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(entitys)){
            for (PaasFormSubDataEntity entity : entitys) {
                if (Objects.equals(DistributorEnum.SHIPPING_ADDRESS.getAttr(), entity.getAttr())){
                    ContractSubDataExt contractSubDataExt = new ContractSubDataExt();
                    contractSubDataExt.setData(entity.getData());
                    contractSubDataExt.setFormId(entity.getFormId());
                    contractSubDataExt.setId(entity.getId());
                    contractSubDataExt.setDataId(entity.getId());
                    List<ContractSubDataExt> shippingAddress = shippingAddressMap.get(entity.getDataId());
                    if (shippingAddress == null) {
                        shippingAddress = new ArrayList<>();
                    }
                    shippingAddress.add(contractSubDataExt);
                    shippingAddressMap.put(entity.getDataId(), shippingAddress);
                }
            }
        }
        fieldAttrEntityForImport.setShippingAddressMap(shippingAddressMap);
    }

    /**
     * es批量查询数据封装到解释
     * 返回的结果是{name:id}的对应关系
     *
     * @param attr                         属性
     * @param selectAttr                   属性在其关联业务的attr
     * @param titlePojoList                标题
     * @param corpid                       公司id
     * @param rowValueList                 每组第一条数据的集合或所有行数据
     * @param indexTypeEnum                索引
     * @param fieldAttrEntityForImportList 解释
     * @throws XbbException 异常
     */
    private QueryLinkBusinessToPutValuePojo queryLinkBusinessToPutValue(String attr, String subAttr, String selectAttr, List<CellTitlePojo> titlePojoList, String corpid, List<List<CellValuePojo>> rowValueList, IndexTypeEnum indexTypeEnum, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        QueryLinkBusinessToPutValuePojo queryLinkBusinessToPutValuePojo = new QueryLinkBusinessToPutValuePojo();
        Map<String, Long> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        FieldAttrEntityForImport fieldAttrEntityForImport = null;
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
                break;
            }
        }

        if (Objects.isNull(fieldAttrEntityForImport)) {
            queryLinkBusinessToPutValuePojo.setFieldAttrEntityForImport(new FieldAttrEntityForImport());
            queryLinkBusinessToPutValuePojo.setParentProductNoAndId(map);
            return queryLinkBusinessToPutValuePojo;
        }
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        List<Object> attrValues = new ArrayList<>();
        Integer columnIndex;
        String title = null;
        String parentTitle = null;
        if (subAttr == null) {
            title = fieldAttrEntityForImport.getAttrName();
        } else {
            parentTitle = fieldAttrEntityForImport.getAttrName();
            List<? extends FieldAttrEntity> items = fieldAttrEntityForImport.getSubForm().getItems();
            for (int i = 0; i < items.size(); i++) {
                if (Objects.equals(subAttr, items.get(i).getAttr())) {
                    title = items.get(i).getAttrName();
                    break;
                }
            }
        }
        columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, title, parentTitle);
        for (List<CellValuePojo> cellValueList : rowValueList) {
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                continue;
            }
            if (cellValue.toString().contains(StringConstant.COMMA) || cellValue.toString().contains(StringConstant.CHINESE_COMMA)) {
                // TODO 如果数据本生包含逗号，这样粗暴的分割就会有问题
                cellValue = cellValue.toString().replaceAll(StringConstant.CHINESE_COMMA, StringConstant.COMMA);
                List<String> singRowDataValues = Arrays.asList(cellValue.toString().split(StringConstant.COMMA));
                attrValues.addAll(singRowDataValues);
            } else {
                attrValues.add(cellValue);
            }
        }
        Map<String, Object> linkBusinessMap = fieldAttrEntityForImport.getLinkBusinessMap();
        if (Objects.isNull(linkBusinessMap)) {
            linkBusinessMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
//        else {
//            // BUG 19449
//            Iterator<String> mapIterator = linkBusinessMap.keySet().iterator();
//            while (mapIterator.hasNext()) {
//                String key = mapIterator.next();
//                Object value = linkBusinessMap.get(key);
//                // 导入超过1000条时需要取到原先的map，但是产品的map是经过多次转换，存的是list，需要删除
//                if (!(value instanceof Long || value instanceof String)) {
//                    mapIterator.remove();
//                }
//            }
//        }
        List<String> repeatErrorKey = fieldAttrEntityForImport.getRepeatErrorKey();
        if (Objects.isNull(repeatErrorKey)) {
            repeatErrorKey = new ArrayList<>();
        }

        if (attrValues.isEmpty()) {
            fieldAttrEntityForImport.setRepeatErrorKey(repeatErrorKey);
            fieldAttrEntityForImport.setLinkBusinessMap(linkBusinessMap);

            queryLinkBusinessToPutValuePojo.setFieldAttrEntityForImport(fieldAttrEntityForImport);
            queryLinkBusinessToPutValuePojo.setParentProductNoAndId(map);
            return queryLinkBusinessToPutValuePojo;
        }
        // 需要查询的字段
        List<String> fieldList;
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        if (Objects.equals(selectAttr, FieldTypeEnum.SERIALNO.getAlias())) {
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.SERIALNO.getAlias() + keyword, attrValues));
            fieldList = Arrays.asList(FieldTypeEnum.SERIALNO.getAlias(), FieldTypeEnum.DATAID.getAlias(), StringConstant.SAAS_LINK_BUSINESS_ID);
        } else {
            String selectAttrStr = "data." + selectAttr;
            fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), selectAttrStr, StringConstant.SAAS_LINK_BUSINESS_ID);
            boolQueryBuilder.filter(termsQuery(esData + selectAttr + keyword, attrValues));
        }
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCT)) {
            // 只查询父产品
            boolQueryBuilder.filter(termQuery( esData + ProductEnum.PARENT_ID.getAttr(), 0));
        }
        List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);


//        Map<String, Object> map = fieldAttrEntityForImport.getLinkBusinessMap() == null ? new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY) : fieldAttrEntityForImport.getLinkBusinessMap();
        List<String> repeatKey = fieldAttrEntityForImport.getRepeatErrorKey() == null ? new ArrayList<>() : fieldAttrEntityForImport.getRepeatErrorKey();
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityList) {
            JSONObject data = paasFormDataEntityExt.getData();
            String key;
            if (Objects.equals(selectAttr, FieldTypeEnum.SERIALNO.getAlias())) {
                key = paasFormDataEntityExt.getSerialNo();
            } else {
                key = FastJsonHelper.getStringOrDefaultFromFormData(data, selectAttr, "");
            }
            if (map.containsKey(key)) {
                repeatKey.add(key);
            }
            Long dataId = paasFormDataEntityExt.getDataId();
            if (Objects.nonNull(dataId)) {
                map.put(key, dataId);
            } else if (Objects.nonNull(paasFormDataEntityExt.getId())) {
                map.put(key, paasFormDataEntityExt.getId());
            }
        }
        // 不是产品的需要将关联数据放进去，产品的在外层方法queryChildProductToPutValue中置入linkBusinessMap
        if (!Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCT)) {
            linkBusinessMap.putAll(map);
        }
        repeatErrorKey.addAll(repeatKey);
        fieldAttrEntityForImport.setLinkBusinessMap(linkBusinessMap);
        fieldAttrEntityForImport.setRepeatErrorKey(repeatErrorKey);

        queryLinkBusinessToPutValuePojo.setFieldAttrEntityForImport(fieldAttrEntityForImport);
        queryLinkBusinessToPutValuePojo.setParentProductNoAndId(map);
        return queryLinkBusinessToPutValuePojo;
    }

    /**
     * es批量查询数据封装到解释
     * 返回的结果是{name:entity}的对应关系
     *
     * @param attr                         属性
     * @param selectAttr                   属性在其关联业务的attr
     * @param titlePojoList                标题
     * @param corpid                       公司id
     * @param rowValueList                 每组第一条数据的集合或所有行数据
     * @param indexTypeEnum                索引
     * @param fieldAttrEntityForImportList 解释
     * @throws XbbException 异常
     */
    private FieldAttrEntityForImport queryLinkBusinessToPutValueAllField(String attr, String subAttr, String selectAttr, List<CellTitlePojo> titlePojoList, String corpid, List<List<CellValuePojo>> rowValueList, IndexTypeEnum indexTypeEnum, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        FieldAttrEntityForImport fieldAttrEntityForImport = new FieldAttrEntityForImport();
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
                break;
            }
        }
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        List<Object> attrValues = new ArrayList<>();
        Integer columnIndex;
        String title = null;
        String parentTitle = null;
        if (subAttr == null) {
            title = fieldAttrEntityForImport.getAttrName();
        } else {
            parentTitle = fieldAttrEntityForImport.getAttrName();
            List<? extends FieldAttrEntity> items = fieldAttrEntityForImport.getSubForm().getItems();
            for (int i = 0; i < items.size(); i++) {
                if (Objects.equals(subAttr, items.get(i).getAttr())) {
                    title = items.get(i).getAttrName();
                    break;
                }
            }
        }
        columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, title, parentTitle);
        for (List<CellValuePojo> cellValueList : rowValueList) {
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                continue;
            }
            if (cellValue.toString().contains(StringConstant.COMMA)) {
                // TODO 如果数据本生包含逗号，这样粗暴的分割就会有问题
                List<String> singRowDataValues = Arrays.asList(cellValue.toString().split(StringConstant.COMMA));
                attrValues.addAll(singRowDataValues);
            } else {
                attrValues.add(cellValue);
            }
        }
        if (attrValues.isEmpty()) {
            return fieldAttrEntityForImport;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        if (Objects.equals(selectAttr, FieldTypeEnum.SERIALNO.getAlias())) {
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.SERIALNO.getAlias() + keyword, attrValues));
        } else {
            boolQueryBuilder.filter(termsQuery(esData + selectAttr + keyword, attrValues));
        }
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCT)) {
            // 只查询父产品
            boolQueryBuilder.filter(termQuery( esData + ProductEnum.PARENT_ID.getAttr(), 0));
        }
        List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, null);
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> repeatKey = new ArrayList<>();

        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityList) {
            JSONObject data = paasFormDataEntityExt.getData();
            String key;
            if (Objects.equals(selectAttr, FieldTypeEnum.SERIALNO.getAlias())) {
                key = paasFormDataEntityExt.getSerialNo();
            } else {
                key = FastJsonHelper.getStringOrDefaultFromFormData(data, selectAttr, "");
            }
            if (map.containsKey(key)) {
                repeatKey.add(key);
            }
            map.put(key, paasFormDataEntityExt);
        }
        Map<String, Object> linkBusinessMap = fieldAttrEntityForImport.getLinkBusinessMap();
        if (Objects.isNull(linkBusinessMap)) {
            linkBusinessMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        linkBusinessMap.putAll(map);
        List<String> repeatErrorKey = fieldAttrEntityForImport.getRepeatErrorKey();
        if (Objects.isNull(repeatErrorKey)) {
            repeatErrorKey = new ArrayList<>();
        }
        repeatErrorKey.addAll(repeatKey);
        fieldAttrEntityForImport.setLinkBusinessMap(linkBusinessMap);
        fieldAttrEntityForImport.setRepeatErrorKey(repeatErrorKey);
        return fieldAttrEntityForImport;
    }

    /**
     * es批量查询数据封装到解释
     * @param attr                          属性
     * @param subAttr                       子表单的子属性
     * @param selectAttr                    属性在其关联业务的attr
     * @param relyAttr                      依赖的attr
     * @param relaySubAttr                  依赖的subAttr
     * @param relySelectAttr                属性在其关联业务的attr
     * @param titlePojoList                 标题
     * @param corpid                        公司id
     * @param rowValueList                  每组第一条数据的集合或所有行数据
     * @param indexTypeEnum                 索引
     * @param fieldAttrEntityForImportList  解释
     * @return                              解释
     * @throws XbbException                 异常
     */
    private FieldAttrEntityForImport queryHavaLinkAttrToPutValue(String attr, String subAttr, String selectAttr, String relyAttr, String relaySubAttr, String relySelectAttr,List<CellTitlePojo> titlePojoList, String corpid, List<List<CellValuePojo>> rowValueList, IndexTypeEnum indexTypeEnum, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        FieldAttrEntityForImport fieldAttrEntityForImport = null;
        FieldAttrEntityForImport relyAttrField = null;
        for (FieldAttrEntityForImport needQueryAttrEntity : fieldAttrEntityForImportList) {
            if (Objects.equals(needQueryAttrEntity.getAttr(), attr)) {
                fieldAttrEntityForImport = needQueryAttrEntity;
            } else if (Objects.equals(needQueryAttrEntity.getAttr(), relyAttr)) {
                relyAttrField = needQueryAttrEntity;
            }
            if (Objects.nonNull(fieldAttrEntityForImport) && Objects.nonNull(relyAttrField)) {
                break;
            }
        }
        if (Objects.isNull(fieldAttrEntityForImport) || Objects.isNull(relyAttrField)) {
            return new FieldAttrEntityForImport();
        }
        Map<String, Object> relyAttrFieldLinkBusinessMap = relyAttrField.getLinkBusinessMap();
        List<Object> linkIds = new ArrayList<>();
        if (Objects.nonNull(relyAttrFieldLinkBusinessMap)) {
            relyAttrFieldLinkBusinessMap.values().forEach(obj -> {
                if (obj instanceof List) {
                    PaasFormDataEntityExt paasFormDataEntityExt = ((List<PaasFormDataEntityExt>) obj).get(0);
                    linkIds.add(paasFormDataEntityExt.getId());
                } else if (obj instanceof String || obj instanceof Long) {
                    linkIds.add(obj);
                } else {
                    PaasFormDataEntityExt paasFormDataEntityExt = (PaasFormDataEntityExt) obj;
                    linkIds.add(paasFormDataEntityExt.getId());
                }
            });
        }
        String esData = StringConstant.JSON_DATA + StringConstant.POINT;
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        List<Object> attrValues = new ArrayList<>();
        Integer columnIndex;
        String title = null;
        String parentTitle = null;
        if (subAttr == null) {
            title = fieldAttrEntityForImport.getAttrName();
        } else {
            parentTitle = fieldAttrEntityForImport.getAttrName();
            List<? extends FieldAttrEntity> items = fieldAttrEntityForImport.getSubForm().getItems();
            for (int i = 0; i < items.size(); i++) {
                if (Objects.equals(subAttr, items.get(i).getAttr())) {
                    title = items.get(i).getAttrName();
                    break;
                }
            }
        }
        columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, title, parentTitle);
        for (List<CellValuePojo> cellValueList : rowValueList) {
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                continue;
            }
            if (cellValue.toString().contains(StringConstant.COMMA)  || cellValue.toString().contains(StringConstant.CHINESE_COMMA)) {
                cellValue = cellValue.toString().replaceAll(StringConstant.CHINESE_COMMA, StringConstant.COMMA);
                List<String> singRowDataValues = Arrays.asList(cellValue.toString().split(StringConstant.COMMA));
                attrValues.addAll(singRowDataValues);
            } else {
                attrValues.add(cellValue);
            }
        }
        if (attrValues.isEmpty()) {
            return fieldAttrEntityForImport;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        if (Objects.equals(selectAttr, FieldTypeEnum.SERIALNO.getAlias())) {
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.SERIALNO.getAlias() + keyword, attrValues));
        } else {
            boolQueryBuilder.filter(termsQuery(esData + selectAttr + keyword, attrValues));
        }
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
        if (Objects.nonNull(relyAttrFieldLinkBusinessMap)) {
            boolQueryBuilder.filter(termsQuery(esData + relySelectAttr + keyword, linkIds));
        }
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PRODUCT)) {
            // 只查询父产品
            boolQueryBuilder.filter(termQuery( esData + ProductEnum.PARENT_ID.getAttr(), 0));
        }
        List<SortBuilder> sortBuilderList = null;
        if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN)) {
            // 1.筛选出“未跟进”、“已延期”状态的访客计划；
            boolQueryBuilder.filter(termsQuery( esData + CommunicatePlanEnum.STATUS.getAttr(), Arrays.asList(CommunicatePlanStatusEnum.NO_FOLLOW.getCode(), CommunicatePlanStatusEnum.DELAY.getCode())));
            sortBuilderList = Collections.singletonList(new FieldSortBuilder(CommunicatePlanEnum.getAttrConnectData(CommunicatePlanEnum.COMMUNICATE_TIME)).order(SortOrder.ASC));
        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
        List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, null, sortBuilderList);
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityList) {
            JSONObject data = paasFormDataEntityExt.getData();
            String key;
            if (Objects.equals(selectAttr, FieldTypeEnum.SERIALNO.getAlias())) {
                key = paasFormDataEntityExt.getSerialNo();
            } else {
                key = FastJsonHelper.getStringOrDefaultFromFormData(data, selectAttr, "");
            }
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = new ArrayList<>();
            if (map.containsKey(key)) {
                paasFormDataEntityExtList = (List<PaasFormDataEntityExt>)map.get(key);
            }
            paasFormDataEntityExtList.add(paasFormDataEntityExt);
            map.put(key, paasFormDataEntityExtList);
        }
        Map<String, Object> linkBusinessMap = fieldAttrEntityForImport.getLinkBusinessMap();
        if (Objects.isNull(linkBusinessMap)) {
            linkBusinessMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        linkBusinessMap.putAll(map);
        fieldAttrEntityForImport.setLinkBusinessMap(linkBusinessMap);
        return fieldAttrEntityForImport;
    }

    /**
     * 查询子产品
     *
     * @param attr                         属性
     * @param subAttr                      子属性
     * @param selectAttr
     * @param titlePojoList
     * @param corpid
     * @param rowValueList
     * @param indexTypeEnum
     * @param fieldAttrEntityForImportList
     * @throws XbbException
     */
    private Set<Long> queryChildProductToPutValue(String attr, String subAttr, String selectAttr, List<CellTitlePojo> titlePojoList, String corpid, List<List<CellValuePojo>> rowValueList, IndexTypeEnum indexTypeEnum, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        QueryLinkBusinessToPutValuePojo queryLinkBusinessToPutValuePojo = queryLinkBusinessToPutValue(attr, subAttr, selectAttr, titlePojoList, corpid, rowValueList, indexTypeEnum, fieldAttrEntityForImportList);

        FieldAttrEntityForImport fieldAttrEntityForImport = queryLinkBusinessToPutValuePojo.getFieldAttrEntityForImport();

        // key是selectAttr value是dataId
        Map<String, Long> parentProductNoAndId = queryLinkBusinessToPutValuePojo.getParentProductNoAndId();
//        Map<String, Object> linkBusinessMap = fieldAttrEntityForImport.getLinkBusinessMap();


        Set<Long> enableMutilUnitParentIdSet = new HashSet<>();
        if (Objects.isNull(parentProductNoAndId) || parentProductNoAndId.isEmpty()) {
            return enableMutilUnitParentIdSet;
        }
        Map<Object, String> linkBusinessAgainstMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 父产品id是key 编号是value
        for (Map.Entry<String, Long> entry : parentProductNoAndId.entrySet()) {
            linkBusinessAgainstMap.put(entry.getValue(), entry.getKey());
        }
        Map<String, Object> childProudctMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        String keyWord = StringConstant.POINT + StringConstant.KEY_WORD;
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT + ProductEnum.PARENT_ID.getAttr(), parentProductNoAndId.values()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyWord, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, null);


        Map<Long, List<PaasFormDataEntityExt>> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityList) {
            Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), ProductEnum.PARENT_ID.getAttr(), 0L);
            List<PaasFormDataEntityExt> parentIdDataList = productMap.get(parentId) == null ? new ArrayList<>() : productMap.get(parentId);
            parentIdDataList.add(paasFormDataEntityExt);
            productMap.put(parentId, parentIdDataList);
            if (Objects.equals(BasicConstant.ONE, paasFormDataEntityExt.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))){
                enableMutilUnitParentIdSet.add(parentId);
            }
        }
        // 返回 编号为key，实体list为value
        for (Map.Entry<Long, List<PaasFormDataEntityExt>> entry : productMap.entrySet()) {
            if (linkBusinessAgainstMap.containsKey(entry.getKey())) {
                childProudctMap.put(linkBusinessAgainstMap.get(entry.getKey()), entry.getValue());
            }
        }


        Map<String, MultiUnitItemPoJo> groupBaseUnitStringMap = relativeProductHelp.getGroupBaseUnitStringMap(corpid);
        fieldAttrEntityForImport.setGroupBaseUnitMap(groupBaseUnitStringMap);

        Map<String, Object> linkBusinessMap = Objects.nonNull(fieldAttrEntityForImport.getLinkBusinessMap()) ? fieldAttrEntityForImport.getLinkBusinessMap() : new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        linkBusinessMap.putAll(childProudctMap);

        fieldAttrEntityForImport.setLinkBusinessMap(linkBusinessMap);
        return enableMutilUnitParentIdSet;
    }

    @Override
    public ExportFormDataVO  exportFormData(FormDataListDTO formDataListDTO) throws XbbException {
        //如果是自定义导出，一个字段都没有选择，抛出异常
        boolean partialExportFlag = null!=formDataListDTO.getExcelPartialExportPojo()
                && Objects.equals(formDataListDTO.getExcelPartialExportPojo().getPartialExport(),1);
        if ( partialExportFlag && CollectionsUtil.isEmpty(formDataListDTO.getExcelPartialExportPojo().getPartialSelectAttrs()) ) {
            //是否选择了字段，没有选择抛出异常
            throw new XbbException(ExportErrorCodeEnum.API_ERROR_234007);
        }

        // 读取导出任务状态缓存
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();
        String userName = formDataListDTO.getLoginUserName();
        String hashKey = corpid + "_" + userId;
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);

        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);
        // 将id拼进condition
        formDataListDTO.setConditions(formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions());
        List<Long> idIn = formDataListDTO.getIdIn();
        Integer distributorMark = formDataListDTO.getDistributorMark();
        Integer businessType = formDataListDTO.getBusinessType();
        if (idIn != null && !idIn.isEmpty()) {
            if (Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(), businessType)) {
                //预收款余额、预付款余额的es内没有dataId字段
                formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.SAAS_LINK_BUSINESS_ID, new ArrayList<>(idIn), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
            } else {
                formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(idIn), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
            }
        }
        formDataListDTO.setPage(1);
        formDataListDTO.setPageSize(10000);

        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        if (Objects.equals(formDataListDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
            long startTime = DateTimeUtil.getLong();
            LOG.warn("export_" + corpid + "_" + userId + "_paas_start,time=" + DateTimeUtil.getString(startTime));
            // PaaS导出
            exportPaasFormData(formDataListDTO);
            long endTime = DateTimeUtil.getLong();
            LOG.warn("export_" + corpid + "_" + userId + "_paas_end,time=" + DateTimeUtil.getString(endTime) + ",spendTime=" + DateTimeUtil.secondToTime((endTime - startTime) / 1000));
        } else {
            // SaaS导出
            Integer subBusinessType = formDataListDTO.getSubBusinessType();
            if ((Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.STOCK_SEARCH.getCode()))
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_PURCHASE.getCode())
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())
                    || Objects.equals(subBusinessType, XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
                businessType = subBusinessType;
            }
            if (ExcelConstant.LARGE_NUM_BUSINESS.contains(businessType)) {
                // 最多导出 50000 条；从数据库里查询5万条
                exportFormDataVO = paasExcelExportHelp.exportLargeSaasFormData(formDataListDTO, businessType, partialExportFlag, 50000);
            } else if (ExcelConstant.FIFTY_THOUSAND_BUSINESS.contains(businessType)) {
                // 最多导出50000条；
                exportFormDataVO = paasExcelExportHelp.exportLargeSaasFormData(formDataListDTO, businessType, partialExportFlag, 10000);
            }  else {
                exportFormDataVO = paasExcelExportHelp.exportSaasFormData(formDataListDTO, businessType, partialExportFlag);
            }
        }
        // OSS上传文件
//        String downloadUrl = handleImportService.exportAsync(formDataListDTO, exportFormDataVO, ImportConstant.EXCEL_SUFFIX);
//        exportFormDataVO.setUrl(downloadUrl);
        return exportFormDataVO;
    }








    @Override
    public ExportFormDataVO exportPaasFormData(FormDataListDTO formDataListDTO) throws XbbException {
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        try {
            formDataListDTO.setSearchSubForm(true);
            PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.listByEs(formDataListDTO);
            if (Objects.isNull(paasFormDataEsListVO)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            // paas导出日志记录
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
            if (paasFormEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            // 解析标题
            Map<String, FieldAttrEntity> explainMap = formDataListDTO.getExplainMap();
            List<FieldAttrEntity> list = new ArrayList<>();
            Iterator<String> iterator = explainMap.keySet().iterator();
            while (iterator.hasNext()) {
                String attr = iterator.next();
                FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
                list.add(fieldAttrEntity);
            }
            List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();

            List<String> paasTitle = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList){
                JSONObject data = paasFormDataEntityExt.getData();
                List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(paasFormEntityExt.getCustomTitle()), explainMap, data, list, paasFormDataEntityExt);
                String title = "--";
                if(!formTitleList.isEmpty()){
                    List<Object> value = formTitleList.get(0).getValue();
                    title = value.isEmpty() ? title : value.get(0).toString();
                    paasTitle.add(title);
                }
            }
            String logMemo = StringUtils.join(paasTitle, "，");
            String userId = formDataListDTO.getUserId();
            String userName = formDataListDTO.getLoginUserName();
            String corpid = formDataListDTO.getCorpid();
            if(paasFormDataESList.size() > 1){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, paasFormEntityExt.getName(), paasFormDataESList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                infoArrPojo.setContent(logMemo);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.EXPORT,
                        "", "", memo, formDataListDTO.getHttpHeader());
            } else if (Objects.equals(paasFormDataESList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, paasFormEntityExt.getName(), logMemo);
                mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.EXPORT,
                        paasFormDataESList.get(0).getDataId().toString(), logMemo, memo, formDataListDTO.getHttpHeader());
            }
            // 子表单数据查询
            IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
            paasFormSubDataModel.findSubEntity(corpid, paasFormDataEsListVO.getPaasFormDataESList(), indexTypeEnum);
            paasExcelExportHelp.exportSaasFormData(formDataListDTO, paasFormDataEsListVO);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasExcel数据库导出表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return exportFormDataVO;
    }


    /**
     * 查询所有员工
     *
     * @param corpid
     * @param fieldAttrEntityForImportList
     * @throws XbbException
     */
    private void queryAllUser(String corpid, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<UserEntity> userEntityList = userModel.findEntitys(params);
        Map<String, Object> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (UserEntity userEntity : userEntityList) {
            userMap.put(userEntity.getName(), userEntity.getUserId());
        }
        setUserMap(fieldAttrEntityForImportList, userMap);
    }

    private void setUserMap(List<FieldAttrEntityForImport> fieldAttrEntityForImportList, Map<String, Object> userMap) {
        for (int i = 0; i < fieldAttrEntityForImportList.size(); i ++) {
            FieldAttrEntityForImport fieldAttrEntityForImport = fieldAttrEntityForImportList.get(i);
            if (Objects.equals(FieldTypeEnum.USER.getType(),fieldAttrEntityForImport.getFieldType())
                    || Objects.equals(FieldTypeEnum.USER_GROUP.getType(), fieldAttrEntityForImport.getFieldType())
                    || Objects.equals(FieldTypeEnum.OWNERID.getType(),fieldAttrEntityForImport.getFieldType())
                    || Objects.equals(FieldTypeEnum.COUSERID.getType(),fieldAttrEntityForImport.getFieldType())
                    || Objects.equals(FieldTypeEnum.CREATORID.getType(),fieldAttrEntityForImport.getFieldType())){
                fieldAttrEntityForImportList.get(i).setLinkBusinessMap(userMap);
            }
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldAttrEntityForImport.getFieldType())) {
                List<FieldAttrEntityForImport> subFieldList = JSON.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems()), FieldAttrEntityForImport.class);
                setUserMap(subFieldList, userMap);
                fieldAttrEntityForImport.getSubForm().setItems(subFieldList);
            }
        }
    }

    /**
     * 查询所有部门
     *
     * @param corpid
     * @param fieldAttrEntityForImportList
     * @throws XbbException
     */
    private void queryAllDept(String corpid, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<DepartmentEntity> departmentList = departmentModel.findEntitys(params);
        Map<String, Object> deptMap = new HashMap<>(departmentList.size());
        Map<String, DepartmentEntity> departmentMap = new HashMap<>(departmentList.size());
        departmentList.forEach(item -> departmentMap.put(item.getId().toString(), item));
        for (DepartmentEntity departmentEntity : departmentList) {
            StringBuilder stringBuilder = new StringBuilder();
            String[] routerArr = departmentEntity.getDepIdRouter().substring(1, departmentEntity.getDepIdRouter().length() - 1).split("\\|");
            for (int i = 0; i < routerArr.length; i++) {
                String deptId = routerArr[i];
                if (StringUtil.isNotEmpty(deptId) && departmentMap.containsKey(deptId)) {
                    String name = departmentMap.get(deptId).getName();
                    stringBuilder.append(name).append(PaasConstant.ROLE_DELIMITER);
                }
            }
            if (stringBuilder.length() > 0) {
                deptMap.put(stringBuilder.substring(0, stringBuilder.length() - 1), departmentEntity.getId());
            }
        }
        setDeptMap(fieldAttrEntityForImportList, deptMap);
    }

    private void setDeptMap(List<FieldAttrEntityForImport> fieldAttrEntityForImportList, Map<String, Object> deptMap) {
        for (int i = 0; i < fieldAttrEntityForImportList.size(); i ++) {
            FieldAttrEntityForImport fieldAttrEntityForImport = fieldAttrEntityForImportList.get(i);
            Integer fieldType = fieldAttrEntityForImport.getFieldType();
            if (Objects.equals(FieldTypeEnum.DEPT.getType(), fieldType) || Objects.equals(FieldTypeEnum.DEPT_GROUP.getType(), fieldType)
                    || Objects.equals(FieldTypeEnum.DEPARTMENTID.getType(), fieldType) || Objects.equals(FieldTypeEnum.PURCHASEABLE_GOODS.getType(), fieldType)) {
                fieldAttrEntityForImportList.get(i).setLinkBusinessMap(deptMap);
            }
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType)) {
                // 增加SerializerFeature.DisableCircularReferenceDetect，避免序列化问题
                List<FieldAttrEntityForImport> subFieldList =JSON.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems(), SerializerFeature.DisableCircularReferenceDetect), FieldAttrEntityForImport.class);
                setDeptMap(subFieldList, deptMap);
                fieldAttrEntityForImport.getSubForm().setItems(subFieldList);
            }
        }
    }

    @Override
    public Workbook errorOrUpdateDownLoad(ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        Workbook templateExcel = null;
        Workbook copyWb = null;
        SXSSFWorkbook errorExcel = null;
        try {
            Long formId = excelTemplateDTO.getFormId();
            String userId = excelTemplateDTO.getUserId();
            String corpid = excelTemplateDTO.getCorpid();
            Integer businessType = excelTemplateDTO.getBusinessType();
            PaasMenuEntity paasMenuEntity;
            if (Objects.equals(excelTemplateDTO.getBusinessType(), XbbRefTypeEnum.ORI_STOCK.getCode())) {
                paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setName(XbbRefTypeEnum.ORI_STOCK.getName());
            } else if (Objects.equals(excelTemplateDTO.getBusinessType(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())){
                paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setName(XbbRefTypeEnum.KNOWLEDGE_BASE.getName());
            }else {
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId,corpid);
                if (paasFormEntityExt == null) {
                    throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350004);
                }
            }
            Integer excelType = excelTemplateDTO.getExcelType();
            String redisKey;
            // 是否是下载错误excel
            boolean isError = false;
            if (DownloadExcelTypeEnum.UPDATE.getType() == excelType) {
                redisKey = RedisPrefixConstant.IMPORT_UPDATE_EXCEL_KEY;
            } else if (DownloadExcelTypeEnum.ERROR.getType() == excelType) {
                redisKey = RedisPrefixConstant.IMPORT_ERROR_EXCEL_KEY;
                isError = true;
            } else if (DownloadExcelTypeEnum.NO_SIGN.getType() == excelType) {
                redisKey = RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_KEY;
            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002);
            }
            String hashKey = corpid + "_" + userId + "_" + formId;
            List<String> importList = importRedisHelper.getImportList(redisKey, hashKey);
            List<FieldAttrEntityForImport> explainList = JsonHelperUtil.parseArray(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_EXPLAIN,hashKey),FieldAttrEntityForImport.class);
            errorExcel = new SXSSFWorkbook();
            if (Objects.isNull(importList) || importList.isEmpty()) {
                // 缓存中无数据，直接返回空excel
                return errorExcel;
            }
            // 获取模板excel
            ExcelTemplateVO excelTemplateVO = templateDownLoad(excelTemplateDTO);
            // 杰哥鬼才想出来得copy Excel
            ExcelTemplateVO copyExcel = templateDownLoad(excelTemplateDTO);
            templateExcel = excelTemplateVO.getWorkbook();
            copyWb = copyExcel.getWorkbook();

            List<CellTitlePojo> titleList = handleImportService.getExcelTitle(templateExcel, ImportConstant.TITLE_ROW_INDEX, copyWb);
            Map<String, Integer> titleIndexMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            titleList.forEach(item -> {
                String parent = item.getParentTitle() == null ? "" : item.getParentTitle();
                String secondParent = item.getSecondParentTitle() == null ? "" : item.getSecondParentTitle();
                String thirdParent = item.getThirdParentTitle() == null ? "" : item.getThirdParentTitle();
                titleIndexMap.put(thirdParent + secondParent + parent + item.getTitle(), item.getColumnIndex());
            });

            for (String obj : importList) {
                // 遍历数据，插入workbook
                JSONObject errorObj = JSONObject.parseObject(obj);
                String msg = errorObj.getString("msg");
                String listStr = errorObj.getString("rowGroupPojo");
                JSONObject rowGroupPojo = JsonHelperUtil.parseObject(listStr);
                String rowValueListStr = rowGroupPojo.getString("rowValueList");
                JSONArray rowValueArray = JsonHelperUtil.parseArray(rowValueListStr);
                List<List<CellValuePojo>> rowValueList = new ArrayList<>();
                for (int i = 0; i < rowValueArray.size(); i++) {
                    JSONArray jsonArray = rowValueArray.getJSONArray(i);
                    List<CellValuePojo> cellValuePojoList = JsonHelperUtil.parseArray(jsonArray.toJSONString(), CellValuePojo.class);
                    rowValueList.add(cellValuePojoList);
                }

                boolean isErrorExcel = false;
                if (isError) {
                    CellValuePojo cellValuePojoFirst;
                    for (List<CellValuePojo> valuePojos : rowValueList) {
                        isErrorExcel = true;
                        cellValuePojoFirst = valuePojos.get(0);
                        if (DownloadExcelTypeEnum.ERROR.getMsg().equals(cellValuePojoFirst.getTitle())) {
                            // 已经有错误信息列,不再index后移,并且之前的错误列移除
                            isErrorExcel = false;
                            valuePojos.remove(0);
                        }
                        // 插入错误列
                        CellValuePojo cellValuePojo = new CellValuePojo(msg, DownloadExcelTypeEnum.ERROR.getMsg(),null,0);
                        valuePojos.add(0,cellValuePojo);
                    }
                }
                ExcelUtil.addExcelContent(templateExcel, rowValueList, isErrorExcel, titleIndexMap, explainList, businessType);
            }
        }catch (Exception e) {
            LOG.error("paasExcel.errorOrUpdateDownLoad 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        } finally {
            closeWorkBookException(copyWb);
            if (Objects.nonNull(errorExcel)) {
                try {
                    errorExcel.close();
                } catch (IOException e) {
                    LOG.error("关闭SXSSFWorkbook错误", e);
                }catch (Exception e) {
                    LOG.error("关闭SXSSFWorkbook错误", e);
                }
            }
        }

        return templateExcel;
    }

    @Override
    public ImportStatusVO getImportStatus(BaseDTO baseDTO) throws XbbException {
        ImportStatusVO importStatusVO = new ImportStatusVO();

        String userId = baseDTO.getUserId();
        String corpid = baseDTO.getCorpid();
        String hashKey = corpid + "_" + userId;
        ImportStatusPojo importStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_STATUS_KEY, hashKey), ImportStatusPojo.class);

        String value = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey);

        if (Objects.isNull(importStatusPojo)) {
            if (Objects.nonNull(value)) {
                importStatusVO.setIsImport(true);
                return importStatusVO;
            } else {
                return importStatusVO;
            }
        } else {
            BeanUtil.copyProperties(importStatusPojo, importStatusVO);
            importStatusVO.setIsImport(Objects.equals(value, BasicConstant.ONE_STRING));

            if (importStatusPojo.getFinish()) {
                if (importStatusPojo.getErrorNum() > 1000) {
                    String errorUrl = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_ERROR_EXCEL_OSS_KEY, hashKey);
                    importStatusVO.setErrorUrl(errorUrl);
                }

                if (importStatusPojo.getUpdateNum() > 1000) {
                    String updateUrl = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_UPDATE_EXCEL_OSS_KEY, hashKey);
                    importStatusVO.setUpdateUrl(updateUrl);
                }

                if (importStatusPojo.getNoSignNum() > 1000) {
                    String noSignUrl = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_OSS_KEY, hashKey);
                    importStatusVO.setNoSignUrl(noSignUrl);
                }
            }
            return importStatusVO;
        }

    }

    @Override
    public ExportStatusPojo getExportStatus(BaseDTO baseDTO){
        String userId = baseDTO.getUserId();
        String corpid = baseDTO.getCorpid();
        String hashKey = corpid + "_" + userId;
        return JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
    }

    @Override
    public boolean delImportStatus(BaseDTO baseDTO){
        String userId = baseDTO.getUserId();
        String corpid = baseDTO.getCorpid();
        String hashKey = corpid + "_" + userId;
        ImportStatusPojo importStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_STATUS_KEY, hashKey), ImportStatusPojo.class);
        if (importStatusPojo == null) {
            return true;
        }
        String value = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey);
        if (!Objects.equals(value, BasicConstant.ONE_STRING) || importStatusPojo.getFinish()) {
            // 导入任务已结束，可以清缓存
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_STATUS_KEY,hashKey);
            String formHashKey = hashKey + "_" + importStatusPojo.getFormId();
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_ERROR_EXCEL_KEY, formHashKey);
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_UPDATE_EXCEL_KEY, formHashKey);
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_KEY, formHashKey);
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey);

            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey);

            return true;
        }
        return false;
    }

    @Override
    public ExportFormDataVO exportWorkReportData(WorkReportExportDTO workReportExportDTO) throws XbbException {
        //如果是自定义导出，一个字段都没有选择，抛出异常
        boolean partialExportFlag = null!=workReportExportDTO.getExcelPartialExportPojo()
                && Objects.equals(workReportExportDTO.getExcelPartialExportPojo().getPartialExport(),1);
        if ( partialExportFlag && CollectionsUtil.isEmpty(workReportExportDTO.getExcelPartialExportPojo().getPartialSelectAttrs()) ) {
            //是否选择了字段，没有选择抛出异常
            throw new XbbException(ExportErrorCodeEnum.API_ERROR_234007);
        }
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        String userName = workReportExportDTO.getLoginUserName();
        String userId = workReportExportDTO.getUserId();
        String corpid = workReportExportDTO.getCorpid();
        // 读取导出任务状态缓存
        String hashKey = workReportExportDTO.getCorpid() + "_" + workReportExportDTO.getUserId();
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

        Integer type = workReportExportDTO.getType();
        List<Integer> rightReportType = Arrays.asList(1,2,3);
        if (Objects.isNull(type) || !rightReportType.contains(type)) {
            throw new XbbException(WorkReportErrorCodeEnum.API_ERROR_207013);
        }

        PaasFormDataEsListVO formDataListVO = workReportService.exportList(workReportExportDTO);
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        //如果是部分导出，超过10000条数据选择合并单元格，抛出异常
        boolean mergeCellsFlag = false;
        if (partialExportFlag){
            mergeCellsFlag =  Objects.equals(workReportExportDTO.getExcelPartialExportPojo().getMergeCells(),1) && formDataListVO.getPaasFormDataESList().size() > 10000;
            if (mergeCellsFlag){
                //超过10000条数据选择合并单元格，抛出异常
                throw new XbbException(ExportErrorCodeEnum.API_ERROR_234008);
            }
        }
        PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataESList.get(0);
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(paasFormDataEntityExt, formDataListDTO);
        BeanUtil.copyProperties(workReportExportDTO, formDataListDTO);
        formDataListDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        formDataListDTO.setSubBusinessType(WorkReportTypeEnum.getByType(workReportExportDTO.getType()).getBusinessType());

        // 子表单数据查询
        IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        paasFormSubDataModel.findSubEntity(corpid, formDataListVO.getPaasFormDataESList(), indexTypeEnum);

        paasExcelExportHelp.exportSaasFormData(formDataListDTO, formDataListVO);
        // OSS上传文件
//        String downloadUrl = handleImportService.exportAsync(formDataListDTO, exportFormDataVO, ImportConstant.EXCEL_SUFFIX);
//        exportFormDataVO.setUrl(downloadUrl);

        Runnable runnable = () -> {
            try {
                // 生成日志(导出)
                List<String> logName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String logMemo = null;
                for(PaasFormDataEntityExt dataEntityExt : paasFormDataESList){
                    JSONObject data = dataEntityExt.getData();
                    Long reportDate = FastJsonHelper.getLongOrDefaultFromFormData(data, WorkReportFieldEnum.REPORT_DATE.getAttr(), 0L);
                    String reportName = DateTimeUtil.getStringEpochSecond(reportDate, DateTimeUtil.SDFDate);
                    WorkReportTypeEnum workReportTypeEnum = WorkReportTypeEnum.getByType(workReportExportDTO.getType());
                    switch (workReportTypeEnum) {
                        case DAILY:
                            logMemo = WorkReportEnum.WORKREPORT_DAILY.getName() + "(“" + reportName + "“)";
                            break;
                        case WEEKLY:
                            logMemo = WorkReportEnum.WORKREPORT_WEEKLY.getName() + "(“" + reportName + "“)";
                            break;
                        case MONTHLY:
                            logMemo = WorkReportEnum.WORKREPORT_MONTHLY.getName() + "(“" + reportName + "“)";
                            break;
                        default:
                            break;
                    }
                    logName.add(logMemo);
                }
                logMemo = StringUtils.join(logName, "，");
                boolean excelPartialFlag = Objects.equals(workReportExportDTO.getPartialExport(),1);
                if(excelPartialFlag){
                    logMemo =  ExcelLogUtil.excelPartialExportLog(logMemo,formDataListVO.getExplainMap(),formDataListDTO.getExcelPartialExportPojo().getPartialSelectAttrs());
                }
                if(paasFormDataESList.size() > 1){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.WORK_REPORT.getName(), paasFormDataESList.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                    infoArrPojo.setContent(logMemo);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.WORKREPORT, OperateTypeEnum.EXPORT,
                            "", "", memo, workReportExportDTO.getHttpHeader());
                } else if (Objects.equals(paasFormDataESList.size(), 1)){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.WORK_REPORT.getName(), logMemo);
                    mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.WORKREPORT, OperateTypeEnum.EXPORT,
                            paasFormDataESList.get(0).getDataId().toString(), logMemo, memo, workReportExportDTO.getHttpHeader());
                }
            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportWorkReportData log error", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        return exportFormDataVO;
    }

    @Override
    public ExportFormDataVO exportSignInData(SignInExportDTO signInExportDTO) throws XbbException {
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        String userName = signInExportDTO.getLoginUserName();
        String userId = signInExportDTO.getUserId();
        String corpid = signInExportDTO.getCorpid();
        // 读取导出任务状态缓存
        String hashKey = signInExportDTO.getCorpid() + "_" + signInExportDTO.getUserId();
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

        SignInExportVO signInExportVO = signInService.exportList(signInExportDTO);
        List<SignInEntityExt> signList = signInExportVO.getSignList();

        SignExportDTO signExportDTO = new SignExportDTO();
        signExportDTO.setSignList(signList);
        BeanUtil.copyProperties(signInExportDTO, signExportDTO);
        paasExcelExportHelp.exportSignList(signExportDTO, signInExportDTO);
//        FormDataListDTO formDataListDTO = new FormDataListDTO();
//        BeanUtil.copyProperties(signInExportDTO, formDataListDTO);
//        // OSS上传文件
//        String downloadUrl = handleImportService.exportAsync(formDataListDTO, exportFormDataVO, ImportConstant.EXCEL_SUFFIX);
//        exportFormDataVO.setUrl(downloadUrl);

        Runnable runnable = () -> {
            try {
                // 生成日志(导出)
                List<String> logName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String logMemo = null;
                for(SignInEntityExt signInEntityExt : signList){
                    StringBuilder sb = new StringBuilder();
                    String name = signInEntityExt.getUserName();
                    String addTime = DateTimeUtil.getStringEpochSecond(signInEntityExt.getAddTime(), DateTimeUtil.SDFYMDHM);
                    String log = name == null ? addTime : sb.append(addTime).append("（").append(name).append("）").toString();
                    logName.add(log);
                }
                logMemo = StringUtils.join(logName, "，");
                if(signList.size() > 1){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.SIGNIN.getName(), signList.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                    infoArrPojo.setContent(logMemo);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.SIGNIN, OperateTypeEnum.EXPORT,
                            "", "", memo, signInExportDTO.getHttpHeader());
                } else if (Objects.equals(signList.size(), 1)){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.SIGNIN.getName(), logMemo);
                    mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.SIGNIN, OperateTypeEnum.EXPORT,
                            signList.get(0).getId().toString(), logMemo, memo, signInExportDTO.getHttpHeader());
                }
            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportSignInData log error", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        return exportFormDataVO;
    }

    @Override
    public ExportFormDataVO exportCustomerStatementData(CustomerStatementExportDTO customerStatementExportDTO) throws XbbException {
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        String userName = customerStatementExportDTO.getLoginUserName();
        String userId = customerStatementExportDTO.getUserId();
        String corpid = customerStatementExportDTO.getCorpid();
        // 读取导出任务状态缓存
        String hashKey = corpid + "_" + userId;
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), ExportStatusEnum.EXPORTING.getStatus())) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

        StatementCustomerTableDTO statementCustomerTableDTO = new StatementCustomerTableDTO();
        BeanUtil.copyProperties(customerStatementExportDTO, statementCustomerTableDTO);
        statementCustomerTableDTO.setFromExport(BasicConstant.ONE);
        StatementCustomerTableVO statementCustomerTableVO = customerStatementService.customerTable(statementCustomerTableDTO);
        List<StatementTableDataExportPojo> exportDataList =  statementCustomerTableVO.getExportData();

        customerStatementExportDTO.setTitle(statementCustomerTableVO.getTitle());
        customerStatementExportDTO.setExportData(exportDataList);
        paasExcelExportHelp.exportCustomerStatementList(customerStatementExportDTO);

        Runnable runnable = () -> {
            try {
                // 生成日志(导出)
                List<String> logNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                int size = 0;
                for (int i = 0; i < exportDataList.size(); i++) {
                    if (i == 0 || Objects.equals(i, exportDataList.size() - 1)) {
                        //第一条期初、最下面的合计去掉
                        continue;
                    }
                    size++;
                    StatementTableDataExportPojo exportPojo = exportDataList.get(i);
                    StringBuilder sb = new StringBuilder();
                    String name = exportPojo.getStatementId();
                    String checkingDate = exportPojo.getCheckingDate();
                    String log = name == null ? checkingDate : sb.append(checkingDate).append("（").append(name).append("）").toString();
                    logNameList.add(log);
                }
                String logMemo = StringUtils.join(logNameList, "，");
                if(size > BasicConstant.ONE){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.CUSTOMER_STATEMENT.getName(), size);
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                    infoArrPojo.setContent(logMemo);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER_STATEMENT, OperateTypeEnum.EXPORT,
                            "", "", memo, customerStatementExportDTO.getHttpHeader());
                } else if (Objects.equals(size, BasicConstant.ONE)){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.CUSTOMER_STATEMENT.getName(), logMemo);
                    //size为1，说明exportDataList肯定大于1（没有算第一条的期初）
                    StatementTableDataExportPojo statementTableDataExportPojo = exportDataList.get(BasicConstant.ONE);
                    mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER_STATEMENT, OperateTypeEnum.EXPORT,
                            statementTableDataExportPojo.getStatementId(), logMemo, memo, customerStatementExportDTO.getHttpHeader());
                }
            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportCustomerStatementData log error", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        return exportFormDataVO;
    }

    @Override
    public ExportFormDataVO exportWorkOrderData(FormDataListDTO formDataListDTO) throws XbbException {
        //如果是自定义导出，一个字段都没有选择，抛出异常
        boolean partialExportFlag = null!=formDataListDTO.getExcelPartialExportPojo()
                && Objects.equals(formDataListDTO.getExcelPartialExportPojo().getPartialExport(),1);
        if ( partialExportFlag && CollectionsUtil.isEmpty(formDataListDTO.getExcelPartialExportPojo().getPartialSelectAttrs()) ) {
            //是否选择了字段，没有选择抛出异常
            throw new XbbException(ExportErrorCodeEnum.API_ERROR_234007);
        }
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        try {
            String userId = formDataListDTO.getUserId();
            String userName = formDataListDTO.getLoginUserName();
            String corpid = formDataListDTO.getCorpid();
            // 读取导出任务状态缓存
            String hashKey = formDataListDTO.getCorpid() + "_" + formDataListDTO.getUserId();
            ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
            if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
                // 上次导出任务未结束
                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
            }
            // 上次导出状态缓存清除
            paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            //塞个假进度条
            exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
            paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);
            formDataListDTO.setConditions(formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions());
            List<Long> idIn = formDataListDTO.getIdIn();
            if (idIn != null && !idIn.isEmpty()) {
                formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(idIn), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
            }
            formDataListDTO.setPage(1);
            formDataListDTO.setPageSize(10000);
            workOrderListDataPermissionHelp.listDataPermission(formDataListDTO.getConditions(),formDataListDTO.getShouldConditions(), formDataListDTO.getLoginUser(), formDataListDTO.getDefaultGroup(),formDataListDTO.getListGroupId());
            WorkOrderDataEsListVO workOrderDataEsListVO = workOrderFormDataService.listByEsForExport(formDataListDTO);
            if (Objects.isNull(workOrderDataEsListVO)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            List<WorkOrderEntityExt> paasFormDataESList = workOrderDataEsListVO.getPaasFormDataESList();

            SpecialWorkOrderExportDTO specialWorkOrderExportDTO = new SpecialWorkOrderExportDTO();
            specialWorkOrderExportDTO.setPaasFormDataESList(paasFormDataESList);
            BeanUtil.copyProperties(formDataListDTO, specialWorkOrderExportDTO);
            BeanUtil.copyProperties(workOrderDataEsListVO,specialWorkOrderExportDTO);
            //如果是部分导出，超过10000条数据选择合并单元格，抛出异常
            boolean mergeCellsFlag = false;
            if (partialExportFlag){
                mergeCellsFlag =  Objects.equals(formDataListDTO.getExcelPartialExportPojo().getMergeCells(),1) && paasFormDataESList.size() > 10000;
                if (mergeCellsFlag){
                    //超过10000条数据选择合并单元格，抛出异常
                    throw new XbbException(ExportErrorCodeEnum.API_ERROR_234008);
                }
            }

            paasFormSubDataModel.findSubEntity(corpid, specialWorkOrderExportDTO.getPaasFormDataESList(), IndexTypeEnum.IDX_SAAS_WORK_ORDER_SUB);

            paasExcelExportHelp.exportWorkOrderList(formDataListDTO,specialWorkOrderExportDTO);

            Runnable runnable = () -> {
                try {
                    // 生成日志(导出)
                    List<String> logName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    String logMemo;
                    for(WorkOrderEntityExt workOrderEntityExt : paasFormDataESList){
                        String name = workOrderEntityExt.workOrderName();
                        logName.add(name);
                    }
                    logMemo = StringUtils.join(logName, "，");
                    boolean excelPartialFlag = null!=formDataListDTO.getExcelPartialExportPojo()
                            && Objects.equals(formDataListDTO.getExcelPartialExportPojo().getPartialExport(),1);
                    if(excelPartialFlag){
                        logMemo =  ExcelLogUtil.excelPartialExportLog(logMemo,workOrderDataEsListVO.getExplainMap(),formDataListDTO.getExcelPartialExportPojo().getPartialSelectAttrs());
                    }
                    if(paasFormDataESList.size() > 1){
                        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.WORK_ORDER.getName(), paasFormDataESList.size());
                        List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        InfoArrPojo infoArrPojo = new InfoArrPojo();
                        infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                        infoArrPojo.setContent(logMemo);
                        infoArrPojoList.add(infoArrPojo);
                        mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.WORK, OperateTypeEnum.EXPORT,
                                "", "", memo, formDataListDTO.getHttpHeader());
                    } else if (Objects.equals(paasFormDataESList.size(), 1)){
                        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.WORK_ORDER.getName(), logMemo);
                        mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.WORK, OperateTypeEnum.EXPORT,
                                paasFormDataESList.get(0).getId().toString(), logMemo, memo, formDataListDTO.getHttpHeader());
                    }
                } catch (Exception e) {
                    LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportWorkOrderData log error", e);
                }
            };
            logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasExcel数据库导出表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return exportFormDataVO;
    }

    /**
     * 导出回款计划
     *
     * @param paymentTaskExportDTO
     * @return
     */
    @Override
    public ExportFormDataVO exportPaymentTaskData(PaymentTaskExportDTO paymentTaskExportDTO) throws XbbException{
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        String userName = paymentTaskExportDTO.getLoginUserName();
        String corpid = paymentTaskExportDTO.getCorpid();
        String userId = paymentTaskExportDTO.getUserId();
        // 读取导出任务状态缓存
        String hashKey = paymentTaskExportDTO.getCorpid() + "_" + paymentTaskExportDTO.getUserId();
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

        PaasFormDataEsListVO formDataListVO = saasListService.paymentTaskExport(paymentTaskExportDTO);
        FormDataListDTO formDataListDTO = new FormDataListDTO(); formDataListDTO.setBusinessType(XbbRefTypeEnum.PAYMENT_TASK.getCode());
        formDataListDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        if (paasFormDataESList.isEmpty()) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235005);
        }
        PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataESList.get(0);
        BeanUtil.copyProperties(paasFormDataEntityExt, formDataListDTO);
        BeanUtil.copyProperties(paymentTaskExportDTO, formDataListDTO);
        paasExcelExportHelp.exportSaasFormData(formDataListDTO, formDataListVO);
        Runnable runnable = () -> {
            try {
                // 生成日志(导出)
                List<String> logName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String logMemo = null;
                for(PaasFormDataEntityExt dataEntityExt : paasFormDataESList){
                    logName.add(dataEntityExt.getSerialNo());
                }
                logMemo = StringUtils.join(logName, "，");
                if(paasFormDataESList.size() > 1){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.PAYMENT_TASK.getName(), paasFormDataESList.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                    infoArrPojo.setContent(logMemo);
                    infoArrPojoList.add(infoArrPojo);
//                    mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.PAYMENT_TASK_PUSH_SET, OperateTypeEnum.EXPORT, "", "", memo, formDataListDTO.getHttpHeader());
                } else if (Objects.equals(paasFormDataESList.size(), 1)){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.PAYMENT_TASK.getName(), logMemo);
//                    mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.PAYMENT_TASK_PUSH_SET, OperateTypeEnum.EXPORT, paasFormDataESList.get(0).getDataId().toString(), logMemo, memo, formDataListDTO.getHttpHeader());
                }
            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportPaymentTaskData log error", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);
        return exportFormDataVO;
    }

    @Override
    public UserVO getUserVo(String corpid, String userId) throws XbbException {
        //获取用户和权限信息
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setCorpid(corpid);
        userInfoDTO.setUserId(userId);
        userInfoDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
        userInfoDTO.setPaasPermissionsFlag(true);
        userInfoDTO.setUserDetailFlag(true);
        /**
         *  XbbResponse<UserInfoVO> userInfoResp = userFeignClient.getUserInfo(userInfoDTO);
         *  UserInfoVO userInfo;
         */
        // 不调用pc服务了，直接用service层
        UserInfoVO userInfo = userService.getUserInfo(userInfoDTO);
        return userInfo.getUser();
    }

    @Override
    public ExportPartialExplainVO getExplainList(ExcelExplainGetDTO excelExplainGetDTO) throws XbbException {
        ExportPartialExplainVO exportPartialExplainVO = new ExportPartialExplainVO();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(excelExplainGetDTO,formDataListDTO);
        //如果是签到，抛出异常，签到不支持自定义导出
        if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.SIGNIN.getCode())){
            throw new XbbException(ExportErrorCodeEnum.API_ERROR_234009);
        }
        try {
            //获取菜单的名称开始
            ExcelTemplateDTO excelTemplateDTO = new ExcelTemplateDTO();
            BeanUtil.copyProperties(formDataListDTO, excelTemplateDTO);
            Map<String, Object> explainParam = BeanUtil.convertBean2Map(excelTemplateDTO, true);
            PaasFormExplainEntity paasFormExplainEntity;
            if (Objects.equals(excelExplainGetDTO.getFormId(),0L)){
                paasFormExplainEntity = paasFormExplainModel.getByBusinessType(excelExplainGetDTO.getBusinessType(),excelExplainGetDTO.getCorpid());
                if (Objects.isNull(paasFormExplainEntity)){
                    paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(excelExplainGetDTO.getBusinessType());
                }
            }else {
                // 库存查询，预警查询特殊处理默认字段
                if (Objects.equals(XbbRefTypeEnum.STOCK_SEARCH.getCode(),excelExplainGetDTO.getSubBusinessType())){
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), excelExplainGetDTO.getCorpid());
                    if (Objects.nonNull(paasFormEntityExt)){
                        excelExplainGetDTO.setGroupId(excelExplainGetDTO.getFormId().longValue());
                        if (Objects.equals(String.valueOf(excelExplainGetDTO.getFormId()), String.valueOf(ListGroupEnum.WARNING_SEARCH.getCode()))){
                            excelTemplateDTO.setSubBusinessType(XbbRefTypeEnum.WARNING_SEARCH.getCode());
                        }else if (Objects.equals(String.valueOf(excelExplainGetDTO.getFormId()), String.valueOf(ListGroupEnum.GUARANTEE_SEARCH.getCode()))){
                            excelTemplateDTO.setSubBusinessType(XbbRefTypeEnum.GUARANTEE_SEARCH.getCode());
                        }
                        excelExplainGetDTO.setFormId(paasFormEntityExt.getId());
                    }
                }
                paasFormExplainEntity = paasFormExplainModel.getByFormId(excelExplainGetDTO.getFormId(),excelExplainGetDTO.getCorpid());
                if (Objects.isNull(paasFormExplainEntity)){
                    paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(excelExplainGetDTO.getBusinessType());
                }
            }
            Long menuId;
            // 过滤不需要导入的字段start
            List<FieldAttrEntity> explainList = new ArrayList<>();
            List<FieldAttrEntityForImport> fieldAttrList = new ArrayList<>();
            //工单特殊处理
            if (Objects.equals(excelExplainGetDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER.getCode())){
                explainParam.remove("menuId");
                explainParam.remove("businessType");
                explainParam.remove("appId");
                List<WorkOrderExplainEntity> formWorkExplainList = workOrderExplainModel.list(explainParam);
                if (formWorkExplainList == null || formWorkExplainList.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                WorkOrderExplainEntity workOrderExplainEntity = formWorkExplainList.get(0);
                menuId = workOrderExplainEntity.getMenuId();
                fieldAttrList = JSON.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntityForImport.class);
            }else if(Objects.equals(excelExplainGetDTO.getBusinessType(),XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())){
                // 产品价目查询特殊处理
                JSONArray fieldAttrJsonArray = importHelper.getFieldAttrList(formDataListDTO.getCorpid());
                paasFormExplainEntity = new PaasFormExplainEntity();
                paasFormExplainEntity.setExplains(fieldAttrJsonArray.toJSONString());
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(formDataListDTO.getBusinessType(), formDataListDTO.getCorpid(), DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
                if (paasFormEntityExt == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                menuId = paasFormEntityExt.getMenuId();
                fieldAttrList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntityForImport.class);
                BeanUtil.copyPropertiesList(fieldAttrList,explainList,FieldAttrEntity.class);
            }else {
                fieldAttrList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntityForImport.class);
                menuId = paasFormExplainEntity.getMenuId();
            }
            //待入库自定义导出解释过滤拼接
            if(Objects.equals(excelExplainGetDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())) {
                customizeImportExplainsWait(excelExplainGetDTO, fieldAttrList);
            }
            //待采购自定义导出解释过滤拼接
            if(Objects.equals(excelExplainGetDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_PURCHASE.getCode())) {
                handleImportService.parseWaitPurchaseExplains(excelExplainGetDTO, fieldAttrList);
            }
            //智能补货自定义导出解释过滤拼接
            if(Objects.equals(excelExplainGetDTO.getSubBusinessType(), XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())) {
                handleImportService.parseSmartReplenishmentExplains(excelExplainGetDTO, fieldAttrList);
            }
            //待出库自定义导出解释过滤拼接
            if(Objects.equals(excelExplainGetDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
                handleImportService.waitOutstockExplains(excelExplainGetDTO, fieldAttrList);
            }
            if (!Objects.equals(excelExplainGetDTO.getBusinessType(),XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())){
                BeanUtil.copyPropertiesList(explainList,fieldAttrList,FieldAttrEntityForImport.class);
            }
            // 过滤不需要导入的字段
            handleImportService.filterUnExportFields(formDataListDTO.getCorpid(), fieldAttrList, formDataListDTO.getSaasMark(), ImportConstant.FROM_EXPORT, formDataListDTO.getBusinessType(), true);
            if (Objects.equals(excelExplainGetDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                // SaaS字段解释特处理
                excelTemplateDTO.setFormImportOrExport(ImportConstant.FROM_EXPORT);
                excelTemplateDTO.setPartialExport(1);
                handleImportService.changeFieldShowTypeForImport(excelTemplateDTO, fieldAttrList);
                handleImportService.handleSpecialExplain(fieldAttrList, excelTemplateDTO);
            } else {
                handleImportService.setTitleTag(fieldAttrList);
            }
            explainList.clear();
            BeanUtil.copyPropertiesList(fieldAttrList,explainList,FieldAttrEntity.class);
            exportPartialExplainVO.setExplainList(explainList);
            // 过滤不需要导入的字段end

            // 获取用户配置的常用字段start
            ColumnSetListDTO columnSetListDTO = new ColumnSetListDTO();
            BeanUtil.copyProperties(excelExplainGetDTO,columnSetListDTO);
            ColumnSetListVO columnSetListVO = userConfigService.columnSetList(columnSetListDTO);
            List<String> columnInvisibleFieldList = (List<String>) columnSetListVO.getUserConfigMap().get("columnInvisibleField");
            if (null != columnInvisibleFieldList){
                exportPartialExplainVO.setColumnInvisibleField(columnInvisibleFieldList);
            }
            // 获取用户配置的常用字段end

            if (Objects.equals(menuId,0L)){
                menuId = excelExplainGetDTO.getMenuId();
            }
            PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(menuId, excelExplainGetDTO.getCorpid());
            String menuName = paasMenuEntity.getName();
            if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                menuName = XbbRefTypeEnum.STOCK_SEARCH.getName();
            } else if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
                menuName = XbbRefTypeEnum.WARNING_SEARCH.getName();
            } else if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                menuName = XbbRefTypeEnum.GUARANTEE_SEARCH.getName();
            }
            menuName = menuName + DateTimeUtil.getString(DateTimeUtil.SDFDate);
            exportPartialExplainVO.setMenuName(menuName);
            //获取菜单的名称结束
        } catch (XbbException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return exportPartialExplainVO;
    }

    @Override
    public ExportCommunicateCountVO getExportCommunicatePlanCount(CommunicatePlanExportDTO communicatePlanExportDTO) throws XbbException {
        CommunicatePlanDTO communicatePlanDTO = new CommunicatePlanDTO();
        BeanUtil.copyProperties(communicatePlanExportDTO, communicatePlanDTO);
        List<ConditionsEntityExt> conditionsEntityExtList = communicatePlanService.setConditionList(communicatePlanDTO);
//        communicatePlanService.setDataCondition(communicatePlanDTO, conditionsEntityExtList);
        // 父子文档查询
        communicatePlanService.setTeamCondition(communicatePlanDTO, conditionsEntityExtList);
        JSONArray planDateArr = communicatePlanExportDTO.getPlanDateArr();
        if (Objects.nonNull(planDateArr) && !planDateArr.isEmpty()) {
            conditionsEntityExtList.add(EsUtil.packageContions(
                    CommunicatePlanEnum.COMMUNICATE_TIME.getAttr(), BasicHelper.timeStrToValueList(planDateArr),
                    ConditionEnum.RANGE, CommunicatePlanEnum.COMMUNICATE_TIME.getFieldType()));
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,null,communicatePlanExportDTO.getCorpid(),XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
        boolQueryBuilder.filter(termQuery("corpid.keyword",  communicatePlanExportDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        Long count = paasEsModel.count(boolQueryBuilder, IndexTypeEnum.IDX_SAAS_COMMUNICATE_PLAN);
        return new ExportCommunicateCountVO(){{setNum(count);}};
    }

    @Override
    public ExportFormDataVO exportCommunicatePlanData(CommunicatePlanExportDTO communicatePlanExportDTO) throws XbbException {
        //如果是自定义导出，一个字段都没有选择，抛出异常
        boolean partialExportFlag = null!=communicatePlanExportDTO.getExcelPartialExportPojo()
                && Objects.equals(communicatePlanExportDTO.getExcelPartialExportPojo().getPartialExport(),1);
        if(partialExportFlag && CollectionsUtil.isEmpty(communicatePlanExportDTO.getExcelPartialExportPojo().getPartialSelectAttrs())) {
            //是否选择了字段，没有选择抛出异常
            throw new XbbException(ExportErrorCodeEnum.API_ERROR_234007);
        }
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        String userName = communicatePlanExportDTO.getLoginUserName();
        String corpid = communicatePlanExportDTO.getCorpid();
        String userId = communicatePlanExportDTO.getUserId();
        // 读取导出任务状态缓存
        String hashKey = communicatePlanExportDTO.getCorpid() + "_" + communicatePlanExportDTO.getUserId();
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

        PaasFormDataEsListVO formDataListVO;
        try{
            formDataListVO = saasListService.communicatePlanList4Export(communicatePlanExportDTO);
        }catch (Exception e){
            LOG.error("-----获取访客计划导出数据失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        FormDataListDTO formDataListDTO = new FormDataListDTO(); formDataListDTO.setBusinessType(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
        formDataListDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        if (paasFormDataESList.isEmpty()) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235005);
        }

        //如果是部分导出，超过10000条数据选择合并单元格，抛出异常
        boolean mergeCellsFlag = false;
        if (partialExportFlag){
            mergeCellsFlag =  Objects.equals(communicatePlanExportDTO.getExcelPartialExportPojo().getMergeCells(),1) && formDataListVO.getPaasFormDataESList().size() > 10000;
            if (mergeCellsFlag){
                //超过10000条数据选择合并单元格，抛出异常
                throw new XbbException(ExportErrorCodeEnum.API_ERROR_234008);
            }
        }

        // 子表单数据查询
        IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        paasFormSubDataModel.findSubEntity(corpid, paasFormDataESList, indexTypeEnum);

        PaasFormDataEntityExt paasFormDataEntityExt = paasFormDataESList.get(0);
        BeanUtil.copyProperties(paasFormDataEntityExt, formDataListDTO);
        BeanUtil.copyProperties(communicatePlanExportDTO, formDataListDTO);
        paasExcelExportHelp.exportSaasFormData(formDataListDTO, formDataListVO);
        // OSS上传文件
//        String downloadUrl = handleImportService.exportAsync(formDataListDTO, exportFormDataVO, ImportConstant.EXCEL_SUFFIX);
//        exportFormDataVO.setUrl(downloadUrl);


        Runnable runnable = () -> {
            try {
                // 生成日志(导出)
                List<String> logName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String logMemo = null;
                for(PaasFormDataEntityExt dataEntityExt : paasFormDataESList){
                    JSONObject data = dataEntityExt.getData();
                    String name = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicatePlanEnum.NAME.getAttr(), "");
                    logName.add(name);
                }
                logMemo = StringUtils.join(logName, "，");
                boolean excelPartialFlag = Objects.equals(communicatePlanExportDTO.getPartialExport(),1);
                if(excelPartialFlag){
                    logMemo =  ExcelLogUtil.excelPartialExportLog(logMemo,formDataListVO.getExplainMap(),communicatePlanExportDTO.getExcelPartialExportPojo().getPartialSelectAttrs());
                }
                if(paasFormDataESList.size() > 1){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.COMMUNICATE_PLAN.getName(), paasFormDataESList.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                    infoArrPojo.setContent(logMemo);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.CommunicatePlan, OperateTypeEnum.EXPORT,
                            "", "", memo, formDataListDTO.getHttpHeader());
                } else if (Objects.equals(paasFormDataESList.size(), 1)){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.COMMUNICATE_PLAN.getName(), logMemo);
                    mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.CommunicatePlan, OperateTypeEnum.EXPORT,
                            paasFormDataESList.get(0).getDataId().toString(), logMemo, memo, formDataListDTO.getHttpHeader());
                }

            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportCommunicatePlanData log error", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        return exportFormDataVO;
    }



    @Override
    public ExportFormDataVO exportNearCustomerFormData(NearCustomerDTO nearCustomerDTO) throws XbbException {
        //如果是自定义导出，一个字段都没有选择，抛出异常
        boolean partialExportFlag = null!=nearCustomerDTO.getExcelPartialExportPojo()
                && Objects.equals(nearCustomerDTO.getExcelPartialExportPojo().getPartialExport(),1);
        if ( partialExportFlag && CollectionsUtil.isEmpty(nearCustomerDTO.getExcelPartialExportPojo().getPartialSelectAttrs()) ) {
            //是否选择了字段，没有选择抛出异常
            throw new XbbException(ExportErrorCodeEnum.API_ERROR_234007);
        }
        ExportFormDataVO exportFormDataVO = new ExportFormDataVO();
        String userName = nearCustomerDTO.getLoginUserName();
        String userId = nearCustomerDTO.getUserId();
        String corpid = nearCustomerDTO.getCorpid();
        // 读取导出任务状态缓存
        String hashKey = nearCustomerDTO.getCorpid() + "_" + nearCustomerDTO.getUserId();
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo != null && Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 上次导出任务未结束
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235004);
        }
        // 上次导出状态缓存清除
        paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);

        //塞个假进度条
        exportStatusPojo = new ExportStatusPojo(ExportConstant.EXPORT_MAX_TOTAL);
        paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY,hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

        PaasFormDataEsListVO formDataListVO = saasListService.nearCustomerList4Export(nearCustomerDTO);
        if (formDataListVO.getPaasFormDataESList().isEmpty()) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235005);
        }

        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(nearCustomerDTO, formDataListDTO);
        formDataListDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        //如果是部分导出，超过10000条数据选择合并单元格，抛出异常
        boolean mergeCellsFlag = false;
        if (partialExportFlag){
            mergeCellsFlag =  Objects.equals(nearCustomerDTO.getExcelPartialExportPojo().getMergeCells(),1) && formDataListVO.getPaasFormDataESList().size() > 10000;
            if (mergeCellsFlag){
                //超过10000条数据选择合并单元格，抛出异常
                throw new XbbException(ExportErrorCodeEnum.API_ERROR_234008);
            }
        }

        // 子表单数据查询
        IndexTypeEnum indexTypeEnum =  indexTypeModel.getSubIndexType(corpid, formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        paasFormSubDataModel.findSubEntity(corpid, formDataListVO.getPaasFormDataESList(), indexTypeEnum);

        paasExcelExportHelp.exportSaasFormData(formDataListDTO, formDataListVO);
        // OSS上传文件
//        String downloadUrl = handleImportService.exportAsync(formDataListDTO, exportFormDataVO, ImportConstant.EXCEL_SUFFIX);
//        exportFormDataVO.setUrl(downloadUrl);

        // 生成日志(导出)
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        Runnable runnable = () -> {
            try {
                List<String> logName = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String logMemo = null;
                for(PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList){
                    JSONObject data = paasFormDataEntityExt.getData();
                    String name = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerManagementEnum.NAME.getAttr(), "");
                    logName.add(name);
                }
                logMemo = StringUtils.join(logName, "，");
                boolean excelPartialFlag = Objects.equals(nearCustomerDTO.getPartialExport(),1);
                if(excelPartialFlag){
                    logMemo =  ExcelLogUtil.excelPartialExportLog(logMemo,formDataListVO.getExplainMap(),nearCustomerDTO.getExcelPartialExportPojo().getPartialSelectAttrs());
                }
                if(paasFormDataESList.size() > 1){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_EXPORT), userName, XbbRefTypeEnum.CUSTOMER_NEARBY.getName(), paasFormDataESList.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS));
                    infoArrPojo.setContent(logMemo);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArrWithoutAsync(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER, OperateTypeEnum.EXPORT,
                            "", "", memo, nearCustomerDTO.getHttpHeader());
                } else if (Objects.equals(paasFormDataESList.size(), 1)){
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_EXPORT), userName, XbbRefTypeEnum.CUSTOMER_NEARBY.getName(), logMemo);
                    mongoLogHelp.buildLogWithoutAsync(corpid, userId, userName, OperateModuleTypeEnum.CUSTOMER, OperateTypeEnum.EXPORT,
                            paasFormDataESList.get(0).getDataId().toString(), logMemo, memo, nearCustomerDTO.getHttpHeader());
                }



            } catch (Exception e) {
                LOG.error("com.xbongbong.paas.service.impl.PaasExcelServiceImpl.exportNearCustomerFormData log error", e);
            }
        };
        logThreadPoolBeanConfig.sysLogThreadPool().execute(runnable);

        return exportFormDataVO;
    }

    @Override
    public boolean delExportStatus(BaseDTO baseDTO){
        String userId = baseDTO.getUserId();
        String corpid = baseDTO.getCorpid();
        String hashKey = corpid + "_" + userId;
        ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), ExportStatusPojo.class);
        if (exportStatusPojo == null) {
            return true;
        }
        if (!Objects.equals(exportStatusPojo.getFinish(), 2)) {
            // 导出任务已结束，可以清缓存
            paasRedisHelper.removeValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey);
            return true;
        }
        return false;
    }


    /**
     * 关闭workbook
     * @param workbook
     */
    private void closeWorkBookException( Workbook workbook) {
        if (Objects.nonNull(workbook)) {
            try {
                workbook.close();
            } catch (IOException e1) {
                LOG.error("关闭workbook错误", e1);
            }catch (Exception e1) {
                LOG.error("关闭workbook错误", e1);
            }
        }
    }

    private void queryProductToPutValue(String attr, Integer businessType, String corpid, String selectAttr, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) {
        FieldAttrEntityForImport fieldAttrEntityForImport = null;
        FieldAttrEntityForImport selectAttrEntity = null;
        for (FieldAttrEntityForImport entityForImport : fieldAttrEntityForImportList) {
            if (Objects.equals(entityForImport.getAttr(), attr)) {
                fieldAttrEntityForImport = entityForImport;
            } else if (Objects.equals(entityForImport.getAttr(), selectAttr)) {
                selectAttrEntity = entityForImport;
            }
        }
        if (Objects.isNull(fieldAttrEntityForImport) || Objects.isNull(fieldAttrEntityForImport.getLinkBusinessMap()) || Objects.isNull(selectAttrEntity)) {
            return;
        }
        if (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode())) {
            List<Long> idList = new ArrayList<>();
            if (Objects.nonNull(fieldAttrEntityForImport.getLinkBusinessMap())) {
                fieldAttrEntityForImport.getLinkBusinessMap().values().forEach(obj -> {
                    PaasFormDataEntityExt paasFormDataEntityExt;
                    if (obj instanceof List) {
                        paasFormDataEntityExt = ((List<PaasFormDataEntityExt>) obj).get(0);
                    } else {
                        paasFormDataEntityExt = (PaasFormDataEntityExt) obj;
                    }
                    idList.add(paasFormDataEntityExt.getId());
                });
            }
            if (idList.isEmpty()) {
                return;
            }
            List<PurchaseProductEntity> purchaseProductEntities = purchaseProductModel.getPurchaseProductByPurchaseIdIn(corpid, idList);
            Map<String, Object> linkBusinessMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            purchaseProductEntities.forEach(item -> {
                String key = item.getPurchaseSheetId().toString();
                if (linkBusinessMap.containsKey(key)) {
                    List<PurchaseProductEntity> purchaseProduct = (List<PurchaseProductEntity>) linkBusinessMap.get(key);
                    purchaseProduct.add(item);
                } else {
                    List<PurchaseProductEntity> purchaseProduct = new ArrayList<>();
                    purchaseProduct.add(item);
                    linkBusinessMap.put(key,purchaseProduct);
                }
            });
            selectAttrEntity.setLinkBusinessMap(linkBusinessMap);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
            List<Long> idList = new ArrayList<>();
            if (Objects.nonNull(fieldAttrEntityForImport.getLinkBusinessMap())) {
                fieldAttrEntityForImport.getLinkBusinessMap().values().forEach(obj -> {
                    PaasFormDataEntityExt paasFormDataEntityExt;
                    if (obj instanceof List) {
                        paasFormDataEntityExt = ((List<PaasFormDataEntityExt>) ((List) obj)).get(0);
                    } else {
                        paasFormDataEntityExt = (PaasFormDataEntityExt) obj;
                    }
                    idList.add(paasFormDataEntityExt.getId());
                });
            }
            if (idList.isEmpty()) {
                return;
            }
            List<ContractProductEntity> contractProductEntities = contractProductModel.getContractProductByContractIdIn(corpid, idList);
            Map<String, Object> linkBusinessMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            contractProductEntities.forEach(item -> {
                String key = item.getContractId().toString();
                if (linkBusinessMap.containsKey(key)) {
                    List<ContractProductEntity> contractProduct = (List<ContractProductEntity>) linkBusinessMap.get(key);
                    contractProduct.add(item);
                } else {
                    List<ContractProductEntity> contractProduct = new ArrayList<>();
                    contractProduct.add(item);
                    linkBusinessMap.put(key,contractProduct);
                }
            });
            selectAttrEntity.setLinkBusinessMap(linkBusinessMap);
        }

    }

    /**
     * 查询全部可采购商品
     * @param corpid
     * @param fieldAttrEntityForImportList
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/1/18 21:44
     * @version 1.0
     */
    private void queryAllPurchaseableGoods(String corpid, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<ProductCategoryEntity> categoryEntityList = productCategoryModel.findEntitys(params);
        Map<String, Object> categoryMap = new HashMap<>(categoryEntityList.size());
        Map<String, ProductCategoryEntity> productCategoryEntityMap = new HashMap<>(categoryEntityList.size());
        categoryEntityList.forEach(item -> productCategoryEntityMap.put(item.getId().toString(), item));
        for (ProductCategoryEntity productCategoryEntity : categoryEntityList) {
            StringBuilder stringBuilder = new StringBuilder();
            String[] routerArr = productCategoryEntity.getRouter().substring(1, productCategoryEntity.getRouter().length() - 1).split("\\|");
            for (int i = 0; i < routerArr.length; i++) {
                String deptId = routerArr[i];
                if (StringUtil.isNotEmpty(deptId) && productCategoryEntityMap.containsKey(deptId)) {
                    String name = productCategoryEntityMap.get(deptId).getName();
                    stringBuilder.append(name).append(PaasConstant.ROLE_DELIMITER);
                }
            }
            if (stringBuilder.length() > 0) {
                categoryMap.put(stringBuilder.substring(0, stringBuilder.length() - 1), productCategoryEntity.getId());
            }
        }
        setDeptMap(fieldAttrEntityForImportList, categoryMap);
    }

    public void customizeImportExplainsWait(ExcelExplainGetDTO excelExplainGetDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntityForImport fieldAttrEntityForImport = iterator.next();
            String attr = fieldAttrEntityForImport.getAttr();
            if (!(Objects.equals(attr, WaitInstockEnum.SHEET_NO.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.PURCHASE_NAME.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.SUPPLIER_ID.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.SIGN_TIME.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.ESTIMATE_ARRIVE_TIME.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.STATUS.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.SIGNER_ID.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.UPDATETIME.getAttr())
                    || Objects.equals(attr, WaitInstockEnum.ADDTIME.getAttr()))) {
                iterator.remove();
            }
            if(Objects.equals(fieldAttrEntityForImport.getAttr(),WaitInstockEnum.SUPPLIER_ID.getAttr())){
                fieldAttrEntityForImport.setAttrName(WaitInstockEnum.SUPPLIER_ID.getAttrName());
            }
            fieldAttrEntityForImport.setEditable(0);
        }
        if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE.getCode())){
            PaasFormExplainEntity paasFormExplainEnt = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.INVENTORY.getCode(), excelExplainGetDTO.getCorpid());
            List<FieldAttrEntityForImport> explains = JSON.parseArray(paasFormExplainEnt.getExplains(), FieldAttrEntityForImport.class);
            for (FieldAttrEntityForImport fieldAttrEntityForImport : explains){
                if (Objects.equals(fieldAttrEntityForImport.getAttr(),InventoryEnum.PRODUCT.getAttr())){
                    fieldAttrEntityForImport.setAttrName("待入库产品");
                    fieldAttrList.add(fieldAttrEntityForImport);
                    break;
                }
            }
        }else if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())){
            PaasFormExplainEntity paasFormExplainEntityProduct = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),excelExplainGetDTO.getCorpid());
            if (paasFormExplainEntityProduct == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //处理产品解释
            List<FieldAttrEntityForImport> explainListProduct = JSONArray.parseArray(paasFormExplainEntityProduct.getExplains(), FieldAttrEntityForImport.class);
            Iterator<FieldAttrEntityForImport> iteratorProduct = explainListProduct.iterator();
            while (iteratorProduct.hasNext()) {
                FieldAttrEntityForImport fieldAttrEntityForImport = iteratorProduct.next();
                String attr = fieldAttrEntityForImport.getAttr();
                if (!(Objects.equals(attr, WaitInstockEnum.PRODUCT_IMGS.getAttr())
                        || Objects.equals(attr, ProductEnum.NAME.getAttr())
                        || Objects.equals(attr, ProductEnum.SERIALNO.getAttr())
                        || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                        || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                        || Objects.equals(attr, ProductEnum.STOCK.getAttr()))) {
                    iteratorProduct.remove();
                }
                fieldAttrEntityForImport.setEditable(0);
            }
            for (FieldAttrEntityForImport fieldAttrEntityForImport:explainListProduct){
                if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.SERIALNO.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitInstockEnum.PRODUCT_NO.getAttr());
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.NAME.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitInstockEnum.PRODUCT_NAME.getAttr());
                    fieldAttrEntityForImport.setAttrName(WaitInstockEnum.PRODUCT_NAME.getAttrName());
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitInstockEnum.SPECIFICATION.getAttr());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.UNIT.getAttr())){
                    fieldAttrEntityForImport.setAttrName(WaitInstockEnum.UNIT.getAttrName());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.STOCK.getAttr())){
                    fieldAttrEntityForImport.setAttrName(WaitInstockEnum.STOCK.getAttrName());
                }
            }
            FieldAttrEntityForImport memoField = new FieldAttrEntityForImport();
            memoField.setAttr(WaitInstockEnum.MEMO.getAttr());
            memoField.setAttrName(WaitInstockEnum.MEMO.getAttrName());
            memoField.setFieldType(WaitInstockEnum.MEMO.getFieldType());
            memoField.setSaasAttr(WaitInstockEnum.MEMO.getSaasAttr());
            memoField.setLinkedType(WaitInstockEnum.MEMO.getLinkedType());
            memoField.setDisableListSort(0);
            explainListProduct.add(memoField);
            fieldAttrList.addAll(explainListProduct);
        }
    }
}
